We can use get_terms
to get subcategories of any given category in WordPress. This will work with WooCommerce and any other custom taxonomy. Here I will create an utility function to show subcategories wherever we need. I will also create a shortcode to show it from post/page editor.
Utility Function
<?php
function careless_print_subcategories_of_parent_category( $term_id, string $taxonomy_name = 'category' ) {
//requires category id
if ( !$term_id ) {
return false;
}
$sub_categories = get_terms (
array(
'taxonomy' => $taxonomy,
'parent' => $term_id,
'hide_empty' => false,
)
);
//term doesn't exist or error
if ( !$sub_categories || is_wp_error( $sub_categories ) ) {
return false;
}
//print
?>
<ul class="sub-categories">
<?php foreach ( $sub_categories as $sub_category ) { ?>
<li><a href="<?php echo get_term_link( $sub_category ); ?>"><?php echo $sub_category->name; ?></a></li>
<?php } ?>
</ul>
<?php
}
This will print a list of subcategories with link to subcategory pages/archives. Works for any custom taxonomy. Default taxonomy is set to category
.
Usage Example:
//print subcategories list of category id 222
careless_print_subcategories_of_parent_category( 222 );
//print subcategories list of WooCommerce product category id 444
careless_print_subcategories_of_parent_category( 444, 'product_cat' );
Function code goes in the functions.php
file of your active theme. And usage can be done from any template file.
Shortcode
<?php
function careless_subcategories_of_parent_category_shortcode( $args ) {
//requires parent category id
if ( !$args || !$args['id'] ) {
return false;
}
//taxonomy
if ( $args['taxonomy'] ) {
$taxonomy = $args['taxonomy'];
} else {
//default is set to category
$taxonomy = 'category';
}
$sub_categories = get_terms (
array(
'taxonomy' => $taxonomy,
'parent' => $args['id'],
'hide_empty' => false,
)
);
//term doesn't exist or error
if ( !$sub_categories || is_wp_error( $sub_categories ) ) {
return false;
}
//print
ob_start(); ?>
<ul class="sub-categories">
<?php foreach ( $sub_categories as $sub_category ) { ?>
<li><a href="<?php echo get_term_link( $sub_category ); ?>"><?php echo $sub_category->name; ?></a></li>
<?php } ?>
</ul>
<?php return ob_get_clean();
}
add_shortcode( 'careless_subcategories', 'careless_subcategories_of_parent_category_shortcode' );
Code goes in the functions.php
file of your active theme.
Usage Example:
//print subcategories list of category id 222
[careless_subcategories id="222"]
//print subcategories list of WooCommerce product category id 444
[careless_subcategories taxonomy="product_cat" id="444"]
Note: avoid using the starting php tag (line 1 of both functions – <?php
) if your functions file already has code.