Issue when using WP_Query inside the main query loop

There is an issue when using WP_Query inside the main query loop. i.e

while ( have_posts() ) : the_post();

  $sub_query = new WP_Query($args);

  while ( $sub_query->have_posts() ):

    $sub_query->the_post();

  endwhile; // End of the sub query loop

  wp_reset_postdata();

endwhile; // End of main the loop

Lets say your sub query loop has these arguments:

$args = array(
  'post_type' => 'the_cpt',
  'tax_query' => array(
    array(
      'taxonomy' => 'the_cpt_tax1',
      'field'    => 'slug',
      'terms'    => 'tax-slug',
    )
  ),
);

Your sub query loop should work just fine and return you the correct results. But when you try to add a search argument (s) the results are all wrong and the the main query loop is messed up. i.e

$args = array(
  's' => 'A search term', // the search argument
  'post_type' => 'the_cpt',
  'tax_query' => array(
    array(
      'taxonomy' => 'the_cpt_tax1',
      'field'    => 'slug',
      'terms'    => 'tax-slug',
    )
  ),
);

In order to fix this issue I had to add a per_get_posts filter hook like this:

add_filter('pre_get_posts', function($query) {

  $search_term = isset($_GET['s_term']) ? $_GET['s_term'] : false;
  $is_the_page = is_page('the-page-slug'); // only run it on the page the sub query loop is on

  if ( $is_the_page && $search_term && $query->is_search() ) {

    $query->set( 's', $search_term );
    $query->set( 'post_type', 'the_cpt' );

  }

});

Not sure if this is happening for other users and if this is a bug in the WP_Query class

Leave a Reply

Your email address will not be published. Required fields are marked *