Show Categories inside SubCategory page

37 Views Asked by At

I added the following to my WordPress theme functions.php file, to show product subcategories inside the WooCommerce product category archive page, and it works well:

add_action('woocommerce_before_shop_loop', 'dcms_show_subcategories');

function dcms_show_subcategories(){
    if ( is_product_category() ){
        $parentid = get_queried_object_id();

        $cat_args = [ 'parent' => $parentid,
                      'hide_empty' => false ];

        $subcategories = get_terms('product_cat', $cat_args);

        if ( count($subcategories ) ){
            echo "<ul class='dcms-subcategories'>";
            foreach ($subcategories as $subcategory) {
                $link = get_category_link($subcategory->term_id);
                $name = $subcategory->name;
                echo "<li><a href='{$link}'>{$name}</a></li>";
            }
            echo "</ul>";
        }
    }
}

Now, I need to show the product categories inside the subcategory product page, but I can't resolve it. Can anyone help me, please?

I searched online, but I didn't find any solution.

1

There are 1 best solutions below

1
LoicTheAztec On

Everything can fit in a unique function that will display first parent terms and then child terms, replacing your current code:

add_action('woocommerce_before_shop_loop', 'display_related_product_category_terms');
function display_related_product_category_terms(){
    if ( is_product_category() ){
        $taxonomy        = 'product_cat';
        $current_term_id = get_queried_object_id();
        $parent_term_ids = get_ancestors( $current_term_id, $taxonomy );
        $children_terms  = get_terms(['taxonomy' => $taxonomy, 'parent' => $current_term_id, 'hide_empty' => false]);

        // Parent categories
        if ( count($parent_term_ids ) ){
            echo "<ul class='dcms-parent-categories'>";
            foreach ($parent_term_ids as $parent_term_id) {
                printf('<li><a href="%s">%s</a></li>',
                    get_term_link($parent_term_id, $taxonomy),
                    get_term($parent_term_id, $taxonomy)->name
                );
            }
            echo "</ul>";
        }

        // Sub categories
        if ( count($children_terms ) ){
            echo "<ul class='dcms-subcategories'>";
            foreach ($children_terms as $children_term) {
                printf('<li><a href="%s">%s</a></li>', 
                    get_term_link($children_term), 
                    $children_term->name
                );
            }
            echo "</ul>";
        }
    }
}

Code goes in functions.php file of your child theme (or in a plugin). Tested and works.