I've found various snippets online to list the woocommerce product categories, but I can't find a snippet that lists the subcategories and sub-sub categories for a given category.
How can I get the subcategories of a given product category?
This is possible with a custom function in which you will set your "parent" product category slug:
function get_product_subcategories_list( $category_slug ){
$terms_html = array();
$taxonomy = 'product_cat';
// Get the product category (parent) WP_Term object
$parent = get_term_by( 'slug', $category_slug, $taxonomy );
// Get an array of the subcategories IDs (children IDs)
$children_ids = get_term_children( $parent->term_id, $taxonomy );
// Loop through each children IDs
foreach($children_ids as $children_id){
$term = get_term( $children_id, $taxonomy ); // WP_Term object
$term_link = get_term_link( $term, $taxonomy ); // The term link
if ( is_wp_error( $term_link ) ) $term_link = '';
// Set in an array the html formated subcategory name/link
$terms_html[] = '<a href="' . esc_url( $term_link ) . '" rel="tag" class="' . $term->slug . '">' . $term->name . '</a>';
}
return '<span class="subcategories-' . $category_slug . '">' . implode( ', ', $terms_html ) . '</span>';
}
Code goes in function.php file of your active child theme (or active theme).
Tested and works.
Usage example:
echo get_product_subcategories_list( 'clothing' );
You will get an horizontal coma separated list (with links) of all subcategories for this given category
This is the code for get subcategory of given category:
$categories = get_the_terms( get_the_ID(), 'product_cat' );
//For checking category exit or not
if ( $categories && ! is_wp_error( $category ) ) :
foreach($categories as $category) :
// get the children (if any) of the current cat
$children = get_categories( array ('taxonomy' => 'product_cat', 'parent' => $category->term_id ));
if ( count($children) == 0 ) {
// if no children, then echo the category name.
echo $category->name;
}
endforeach;
endif;