Site logo

[Resolved] Dynamically list child categories in a widget

Home Forums Support [Resolved] Dynamically list child categories in a widget

Home Forums Support Dynamically list child categories in a widget

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #2580337
    Leonardo

    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!

    #2580377
    David
    Staff
    Customer Support

    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.

Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.