Paul Hoda SEO specialist

Exclude sub category posts from category display WordPress

Sep 29th, 2015Comments Off on Exclude sub category posts from category display WordPress

The code should go in the functions.php file.

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' );

A post can’t belong to both parent category and child category, or you won’t get it displayed.

Autor: