Filtering out child category posts from parent category archive not working

Question

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?

0
, , , , chuck reynolds 7 years 2016-07-06T18:13:44-05:00 0 Answers 85 views 0

Leave an answer

Browse
Browse