WordPress Snippets at WPcustoms

Query: exclude child categories of a specific category

You can exclude children posts on your homepage of category 21 with this function. It only shows the parent category posts but not its children posts. In this example we only show posts from category 21 but not the children posts. Adjust the category ID as needed and customize the conditional tag is_home to specifiy the query.


/**
 * Snippet Name: Query: exclude child categories of a specific category
 * Snippet URL: http://www.wpcustoms.net/snippets/query-exclude-child-categories-specific-category/
 */
     function wpc_exclude_category_children($query) {
        $child_cats = (array) get_term_children('21', 'category');
        if ( $query->is_home ) {
        $query->set('category__not_in', $child_cats);
        return $query;
        }
    }
    add_filter('pre_get_posts', 'wpc_exclude_category_children');