Skip to content
Advertisement

Display sub subcategories terms list on WooCommerce subcategory archive pages

In Woocommerce I use Get the subcategories of the current product category in Woocommerce archives answer function, to display a list of subcategories on the parent category pages

But I only need to apply this to SPECIFIC product-categories though, and to use array with a hunch of category IDs seems not ideal.

I need to display the list only on the first children categories, so for example one of my main parent categories is “Clothing”, then the subcategory “Shirts” and then the sub-sub-category “Sleeveless”. I only need to display it on the first sub-categories, in this example “Shirts”.

Advertisement

Answer

To display only the first subcategory on main category archive pages only use:

add_action('woocommerce_before_shop_loop', 'display_sub_subcategories', 10 );
function display_sub_subcategories() {
    $obj      = get_queried_object();
    $taxonomy = 'product_cat';

    if ( is_a($obj, 'WP_Term') && $taxonomy === $obj->taxonomy && 0 != $obj->parent ) {
        // Get sub-subcategories of the current subcategory
        $terms = get_terms([
            'taxonomy'    => $taxonomy,
            'hide_empty'  => true,
            'parent'      => $obj->term_id
        ]);

        if ( ! empty($terms) ) :

        $output = '<ul class="subcategories-list">';

        // Loop through product subcategories WP_Term Objects
        foreach ( $terms as $term ) {
            $term_link = get_term_link( $term, $taxonomy );

            $output .= '<li class="'. $term->slug .'"><a href="'. $term_link .'">'. $term->name .'</a></li>';
        }

        echo $output . '</ul>';
        endif;
    }
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement