0

I'm merging 2 queries using the code below and it works as I expected except for the $main_query->found_posts; returning 0.

$args = array(
                'post_type' => 'carellcars',
                'posts_per_page' => $per_page,
                'paged' => $cur_page,
                'meta_key' => !empty( $_GET['sortby'] ) ? strpos( $_GET['sortby'], "post_" ) !== false ? "" : $_GET['sortby'] : "", 
                'orderby' => 'rand',
                'order' => 'rand',                      
                'meta_query' => sizeof( $meta_query ) == 1 ? "" : $meta_query 
        );


$args_featured = array(
    'post_type' => 'carellcars',
    'meta_query' => array(
            array(
                'key' => 'featured',
                'value' => 'Yes',
                'compare' => '='
            )
            
    )
    
    );
    
    

//setup your queries as you already do
$featured_query = new WP_Query($args_featured);
$sub_main_query = new WP_Query($args);

//create new empty query and populate it with the other two

$main_query = new WP_Query();
$main_query->posts = array_merge( $featured_query->posts, $sub_main_query->posts );

//populate post_count count for the loop to work correctly
$main_query->post_count = $featured_query->post_count + $sub_main_query->post_count;

echo "<br><br>";
echo $main_query->found_posts;
2
  • Manipulating post_count and posts in your $main_query doesn't do anything to found_posts. If you want $main_query->found_posts to be something other than whatever new WP_Query() returns, you'll need to manipulate it as you are the posts and post_count properties. (It strikes me that there's almost certainly a better way to accomplish what you're trying to do, possibly even in a single query.)
    – Pat J
    Commented Apr 24 at 1:51
  • Why are you running a new query with no arguments and then merging the two queries into it? Why not just merge the arrays from the first two queries and then work through them? It seems like the third query is excessive and not needed as you already have the results returned from the first two. Commented Apr 24 at 19:01

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.