I'm struggling with displaying sub categories limited to only direct children of the parent on category page... I hope someone can help me with that :)
I have working code - when the current category is selected, it displays all its subcategories... but also including grand children and so on...
<?php
$category_id = get_query_var( 'cat' ); // Get current catgory ID
$category = get_term( $category_id, 'category' ); // Fetch category term object
$parent = $category->parent ? $category->parent :
$category_id;
$args = array(
'show_count' => false,
'hide_empty' => true,
'title_li' => '',
'show_option_none' => '',
'echo' => false
);
// Show the children of parent category
if ( $category->parent ) {
$args['child_of'] = $category->parent;
//$args['exclude'] = $category_id; // Don't display the current category in this list
}
else {
$args['child_of'] = $category_id;
}
// Get the category list
$categories_list = wp_list_categories( $args );
if ( $categories_list ) {?>
<div class="subcategory-wrapper">
<ul class="menu">
<?php echo $categories_list; ?>
</ul>
</div>
<?php } ?>
How to display only direct children of current parent category?
What I see now with above code:
=== Current category page selected (parent) ===
Child 01
- Grandchild 01
Child 02
Grand child 01
- Grand grand child 01
Child 03
Child 04
- Grand child 01
What I want to see (even if the parent category has grand children):
=== Current category page selected (parent) ===
Child 01
Child 02
Child 03
Child 04
UPDATE:
to hide grand sub categories, change the $args array to:
$args = array(
'show_count' => false,
'hide_empty' => true,
'depth'=>1,
'title_li' => '',
'show_option_none' => '',
'echo' => false
);
Another problem is that his code doesn't work on the post pages, but only on archive/category pages.
Is there a way to get the same result - show direct children of the parent category to which the post belongs - on the post page?
This is what I have now on the post page:
- Parent category
= = = = = =
Post content here
= = = = = =
This is what I want to have on the post page ( -> I want to display direct children of parent category like the code above does...but unfortunately this code doesn't work on the post page):
Parent category
Child 01 (the post belongs to this subcategory)
Child 02 (the post doesn't belong to this subcategory, but it is displayed, because it's the child of the parent category)
Child 03 (the post doesn't belong to this subcategory, but it is displayed, because it's the child of the parent category) etc.
= = = = = =
Post content here
= = = = = =
Any ideas?
$args
'depth'=>1