I have a post category structure like this:

  • news
  • news / conferences
  • news / newsletter

In Appearance > Menu, I have added 3 menu items.

One each for the categories News, Conferences, Newsletter.

However, the News page also displays posts from Conferences and Newsletter.

How do I exclude posts from subcategories from being displayed in the parent category’s page?

Thanks

6 Answers
6

I rewrote the code from a post at WP Engineer:

function wpse_filter_child_cats( $query ) {

if ( $query->is_category ) {
    $queried_object = get_queried_object();
    $child_cats = (array) get_term_children( $queried_object->term_id, 'category' );

    if ( ! $query->is_admin )
        //exclude the posts in child categories
        $query->set( 'category__not_in', array_merge( $child_cats ) );
    }

    return $query;
}
add_filter( 'pre_get_posts', 'wpse_filter_child_cats' );

Give it a try by pasting the snippet in your functions.php. Please keep in mind that a post can’t belong to both parent category and child category, or you won’t get it displayed.

Tags:

Leave a Reply

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