Exclude ALL posts from sub categories

Need help with a wordpress-task

I want ALL the posts from sub categories to be excluded.

Example:

  • Cake
    • Pie
      • Apple
      • Pear
      • Banana

If i post a post in Banana, i don’t want it to show up in Pie or Cake. I just want posts that are posted in banana to show in banana, not in the top categories.

How can i do this?

I found a code for it to put in functions.php but and it does the trick with the first category, but not the second.

function fb_filter_child_cats($query) {
$cat = get_term_by('name', $query->query_vars['category_name'], 'category');
$child_cats = (array) get_term_children( &$cat->term_id, 'category' );
// also possible
// $child_cats = (array) get_term_children( get_cat_id($query->query_vars['category_name']), 'category' );
if ( !$query->is_admin )
$query->set( 'category__not_in', array_merge($child_cats) );
return $query;
}
add_filter( 'pre_get_posts', 'fb_filter_child_cats' );

4 Answers
4

Don’t change your template, and please do not use query_posts.

Add this to your function.php:

add_action('pre_get_posts', 'filter_out_children');

function filter_out_children( $query ) {
  if ( is_main_query() && is_category() && ! is_admin() ) {
     $qo = $query->get_queried_object();
     $tax_query = array(
       'taxonomy' => 'category',
       'field' => 'id',
       'terms' => $qo->term_id,
       'include_children' => false
     );
     $query->set( 'tax_query', array($tax_query) );
  }
}

Leave a Comment