0

I was having issues when modifying the main query hooking onto pre_get_posts as it was causing the menu to not be displayed. This the original code:

else if ( isset( $_GET['category'] ) && !is_admin()  ) {
    $_GET   = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
    $tax_query = array(
        array(
            'taxonomy' => 'events-category',
            'field' => 'slug',
            'terms' => array( strtolower( $_GET['category'] ) ),
        ),
    );
    $query->set( 'tax_query', $tax_query );
}

Someone suggested to modify the conditional and add $query->is_main_query() to avoid messing up the menu's query:

else if ( isset( $_GET['category'] ) && !is_admin() && $query->is_main_query()  ) {

I did change it and the menus are displayed but the taxonomy query is now completely ignored and all posts are displayed.

Why would $query->is_main_query() modify the taxonomy query? I am completely baffled.

  • 3
    Probably because your theme is not written correctly and uses custom wp_query to display this list of posts... Bit it’s a little bit hard to guess without seeing your code... – Krzysiek Dróżdż May 5 at 12:18
1

In your original setup all category queries on the frontend were affected by the pre_get_posts filter you defined. Hence its interference with the menu query. Then you added an extra condition, is_main_query. The result being that both the menu and your main loop were no longer affected by the filter.

This can mean only one thing. What looks like the main query on your page actually is not. So the filter is not applied.

If you have written this theme yourself you could clean it up so you get the main query and the filter is applied. Otherwise, you could examine the code if there are some arguments set, which you could check with the get method to make sure you are conditionally targeting the right query in stead of using is_main_query.

  • I think you might have nailed it right in the head...I'll do some debugging and report back, appreciate the guidance and the logic in your train of thought! – csaborio May 5 at 15:15
  • That was it. So I am working on a plugin that filters post types based on taxonomies via a drop down menu. I had set the pre_get_posts query correctly, but these were not affecting the main query, so yes, what realised that in my logic, I was creating a new WP_Query to display results when I should've checked that the query already came in and had results in it and should've used that one instead. Bit of a mess, but you definitely helped me catch a very difficult to spot mistakes - thanks again! – csaborio May 5 at 21:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.