Archived topic
Dynamically list child categories in a widget
1 reply · Started by Leonardo on March 24, 2023
Hello!
I need something seemingly simple, but I'm not able to accomplish.
I want to dynamically list child categories in a widget depending on the selected parent category page.
Ex: I have a parent category called "Cameras" and within that category, there are subcategories. When opening the "Cameras" category page, I want this widget to show its child categories.
It's possible?
Thanks!
Hi there,
you could create your own shortcode function with this PHP Snippet:
function list_subcategories_shortcode() {
$categories = get_categories( array(
'child_of' => get_queried_object_id(),
'hide_empty' => false
) );
if ( ! empty( $categories ) ) {
$output = '<ul class="subcategory-list">';
foreach ( $categories as $category ) {
$output .= '<li><a href="' . get_category_link( $category->term_id ) . '">' . $category->name . '</a></li>';
}
$output .= '</ul>';
return $output;
}
return '';
}
add_shortcode( 'list_subcategories', 'list_subcategories_shortcode' );
Then use a Block Element to add your [list_subcategories] shortcode to your archive pages.
It would need some to style.
Let me know.