Display Woocommerce product categories with child and product number in grid

Viewed 75

I have to display product categories grid, where a single column will look like this:

child category
main category
number of products

I am trying to do this with the following code. Instead of "main category" I get the "child" name, which is the same in all cases.

<?php
$taxonomy = 'product_cat';

$parent_cat_ids = get_terms( $taxonomy, array(
    'parent'     => 0,
    'hide_empty' => false,
    'fields'     => 'ids'
) );

$subcategories = get_terms( $taxonomy, array(
    'exclude'     => $parent_cat_ids,
    'orderby'    => 'name',
    'order'      => 'asc',
    'hide_empty' => false,
) );

$category_id = $cat->term_id;

if( ! empty( $subcategories ) ){
    echo '<ul>';
    foreach ($subcategories as $subcategory) {
        echo '<li>
        <h4><a href="'. get_term_link($cat->slug, 'product_cat') .'">'. $cat->name .'</h4>     
        <a href="'. get_term_link($subcategory) .'" >' . $subcategory->name.'</a>
        </li>';
        echo ' ('.$cat->count.')';
    }
    echo '</ul>';
}
?>
0 Answers
Related