Show children for subcategory archives in Woocommerce Product Category widget

Show children for subcategory archives in Woocommerce Product Category widget

4.9/5 - (287 votes)

I'm building a shop with Woocommerce and using WooCommerce Product Category widget. I have set many product categories with subcategories. One of these categories is “Posters” and has several subcategories, like “Star signs”, “Travel”, “Nature”…

By default Woocommerce only shows the parent categories which is good. If I click a category “posters”, I'm redirected to “posters” category archive page and the widget displays all “Posters” children subcategories and it's perfect.

Now, if I click on one of these “Posters” children subcategories, I'm redirected to the respective archive page, but my navigation doesn't show all other “Posters” children subcategories anymore.

The question:
How do I get all parent category and “sibling” subcategories while browsing a subcategory?

Random example of the standard navigation when collapsed:

Phone Cases
Mugs
Pillows
Posters
Shirts
Stickers

Example of navigation when “Posters” has been clicked:

Phone Cases
Mugs
Pillows
Posters
--Star Signs
--Travel
--Nature
--Abstract
--Typography
Shirts
Stickers

When a subcategory is clicked, e.g. “Nature”, the navigation returns to look like the first example given, all collapsed. But I want it to stay expanded like in the second example.

Bellow in the screenshot are my settings for Woocommerce Product Category widget:

Any help will be appreciated.

Your settings are correct. The code below is targeting archives category pages only and it will display now all children subcategories in the Woocommerce Product Category widget, for the current subcategory:

add_filter('woocommerce_product_categories_widget_args', 'widget_product_categories_list_args', 10, 1);
function widget_product_categories_list_args( $list_args ) {
    global $wp_query;

    // Only for category archives pages
    if ( is_tax( $list_args['taxonomy'] ) ):
        // Get current category
        $current_cat = $wp_query->queried_object;

        // Get all Included category terms IDs in the widget
        $included_ids = explode( ',', $list_args['include'] );

        // Get All Childrens Ids from parent term or from current term
        if($current_cat->parent != 0 )
            $childrens = get_term_children( $current_cat->parent, $list_args['taxonomy'] );
        else
            $childrens = get_term_children( $current_cat->term_id, $list_args['taxonomy'] );

        // Loop through Children term Ids and add them to existing included ones
        foreach( $childrens as $child )
            $included_ids[] = $child;

        // Replace included product category term IDs in the $args array
        $list_args['include'] = $included_ids;
    endif;

    return $list_args;
}

Code goes in function.php file of the active child theme (or active theme).

Tested and works.