I would like to dynamically display child categories in a sidebar on category pages using a PHP enabled text widget.
The problem is the widget would need to show the same content on both the parent category and child category pages.
So, on parent category pages it would show the child categories of that category, and on child category pages, all the child categories of that category's parent category.
Ideally, on child category pages it would show all the child categories of that category's parent category except the current (child) category.
This is the code I'm using to get the child categories of the current category's parent category:
<?php if (is_category( )) {
$cat = get_query_var('cat');
$parent = get_category ($cat);
if ($parent->parent) {
wp_list_categories ('child_of=' . $parent->parent);
}
?>
I think I need to change the wp_list_categories
string into an array so I can use the "exclude" parameter so the current child category isn't displayed. I could then add an "else" conditional statement for the parent category.
I would like to dynamically display child categories in a sidebar on category pages using a PHP enabled text widget.
The problem is the widget would need to show the same content on both the parent category and child category pages.
So, on parent category pages it would show the child categories of that category, and on child category pages, all the child categories of that category's parent category.
Ideally, on child category pages it would show all the child categories of that category's parent category except the current (child) category.
This is the code I'm using to get the child categories of the current category's parent category:
<?php if (is_category( )) {
$cat = get_query_var('cat');
$parent = get_category ($cat);
if ($parent->parent) {
wp_list_categories ('child_of=' . $parent->parent);
}
?>
I think I need to change the wp_list_categories
string into an array so I can use the "exclude" parameter so the current child category isn't displayed. I could then add an "else" conditional statement for the parent category.
- It would be nice to show some code, wpse is here for users to help with coding. – Charles Commented Sep 4, 2016 at 1:23
- can you suggest me better way whats you wants on parent cat & child cat page. (describe in if else). parent -> list child cat childpage(if exis child) -> list child cat childpage(not exits) -> Need to display parent cat or all cat ? – Ravi Patel Commented Oct 24, 2017 at 4:47
1 Answer
Reset to default 1After some trial and error I managed to come up with the following:
<?php if (is_category( )) {
$cat = get_query_var('cat');
$thiscat = get_category ($cat);
$parent = $thiscat->parent;
if ($parent != '') {
wp_list_categories( array(
'child_of' => $parent,
'exclude' => $cat
) );
}
else {
wp_list_categories( array(
'child_of' => $cat
) );
}
} ?>
I'm not sure if this is the most efficient method but it does work.