Reputation: 23
I need that each category of Wordpress will display only its own posts and not those of its child categories. How is this done?
I need posts that are in sub-categories to appear only in their sub-categories and not to appear in the parent category (where I want to see only posts that were marked for that parent category. However, in the parent category I get all posts that are marked to appear in the sub-category of that parent category.
For example, if I have category "cars" and underneath it, subcategories "Fiat", Ford", "Honda", I see the Fiat posts both in the subcategory "Fiat" and in the parent category "Cars".
How can we fix that?
Upvotes: 1
Views: 477
Reputation: 9941
Make use of the parse_tax_query
action to exclude children of the current category
You can try something like this: (Requires php 5.3 +)
add_action( 'parse_tax_query', function ( $query ) {
if (
! is_admin()
&& $query->is_main_query()
&& $query->is_category()
) {
$query->tax_query->queries[0]['include_children'] = 0;
}
});
Upvotes: 1
Reputation: 11271
Works only with WordPress >= 3.3.
In your functions.php theme file:
add_filter('pre_get_posts','hide_subcategories_function',20,1);
function hide_subcategories_function($the_query) {
if(get_bloginfo('version') >= 3.3 && function_exists('is_main_query')) {
if(!$the_query->is_admin && !$the_query->is_preview && $the_query->query_vars['suppress_filters'] == false && $the_query->is_category && $the_query->is_main_query()) {
$cat = get_term_by( 'slug', $the_query->query_vars['category_name'], 'category');
$the_query->set('category__in',array($cat->term_id));
}
}
return $the_query ;
}
Upvotes: 0