1

In this example cat 5 is the parent category, and 42 is a sub-category. I the main category 5 archive I don't want any posts from sub-category 42 displaying.

Why isn't this working?

function filter_cat5_archive( $wp_query ) {

    if ( ! is_admin() && $wp_query->is_main_query() && $wp_query->is_category( 5 ) ) {

        $wp_query->set( 'category__not_in', '42' );

    }

}
add_filter( 'pre_get_posts', 'filter_cat5_archive' );

That does nothing. But this following one does filter the results but throws a _doing_it_wrong debug error.

is_main_query was called incorrectly. In pre_get_posts, use the WP_Query->is_main_query() method, not the is_main_query() function. See https://codex.wordpress.org/Function_Reference/is_main_query.

if ( ! is_admin() && is_main_query() && $wp_query->is_category( 5 ) ) {

    $wp_query->set( 'category__not_in', '42' );

}

What am I missing here?

1 Answer 1

0

The is_category function checks the queried object. Since this is in pre_get_posts, the query has not happened yet.

Check the other parameters to find if the query is going to be for cat 5, not if the results are for cat 5. Try ->get('cat').

1
  • so the problem was having $query->is_main_query() in there... If i remove it - works fine. So looking at that I see that it's a custom genesis loop therefore it's not the main query. So doing: if ( ! is_admin() && is_category( 5 ) ) works fine and doesn't seem to cause any other issues. Jul 8, 2016 at 21:14

Your Answer

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

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