Get WooCommerce product categories from WordPress Get WooCommerce product categories from WordPress wordpress wordpress

Get WooCommerce product categories from WordPress


<?php  $taxonomy     = 'product_cat';  $orderby      = 'name';    $show_count   = 0;      // 1 for yes, 0 for no  $pad_counts   = 0;      // 1 for yes, 0 for no  $hierarchical = 1;      // 1 for yes, 0 for no    $title        = '';    $empty        = 0;  $args = array(         'taxonomy'     => $taxonomy,         'orderby'      => $orderby,         'show_count'   => $show_count,         'pad_counts'   => $pad_counts,         'hierarchical' => $hierarchical,         'title_li'     => $title,         'hide_empty'   => $empty  ); $all_categories = get_categories( $args ); foreach ($all_categories as $cat) {    if($cat->category_parent == 0) {        $category_id = $cat->term_id;               echo '<br /><a href="'. get_term_link($cat->slug, 'product_cat') .'">'. $cat->name .'</a>';        $args2 = array(                'taxonomy'     => $taxonomy,                'child_of'     => 0,                'parent'       => $category_id,                'orderby'      => $orderby,                'show_count'   => $show_count,                'pad_counts'   => $pad_counts,                'hierarchical' => $hierarchical,                'title_li'     => $title,                'hide_empty'   => $empty        );        $sub_cats = get_categories( $args2 );        if($sub_cats) {            foreach($sub_cats as $sub_category) {                echo  $sub_category->name ;            }           }    }       }?>

This will list all the top level categories and subcategories under them hierarchically. do not use the inner query if you just want to display the top level categories. Style it as you like.


Improving Suman.hassan95's answer by adding a link to subcategory as well. Replace the following code:

$sub_cats = get_categories( $args2 );    if($sub_cats) {        foreach($sub_cats as $sub_category) {            echo  $sub_category->name ;        }    }

with:

$sub_cats = get_categories( $args2 );            if($sub_cats) {                foreach($sub_cats as $sub_category) {                    echo  '<br/><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>';                }            }

or if you also wish a counter for each subcategory, replace with this:

$sub_cats = get_categories( $args2 );            if($sub_cats) {                foreach($sub_cats as $sub_category) {                    echo  '<br/><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>';                    echo apply_filters( 'woocommerce_subcategory_count_html', ' <span class="cat-count">' . $sub_category->count . '</span>', $category );                }            }


You could also use wp_list_categories();

wp_list_categories( array('taxonomy' => 'product_cat', 'title_li'  => '') );