You can't use get_category()
or get_term()
directly with an ID everywhere. You need to use more arguments listed in here (see the example below). On the templates, I think that also it depends on the displayed products (If they have this category or subcategory).
To retrieve the desired category object you will need to do it by category slug and you will use get_category_by_slug('the_slug')
instead. Then you can retrieve the ID with:
$idObj = get_category_by_slug('my_category_slug');
$id = $idObj->term_id;
Others useful WordPress functions:
To retrieve category name based on category ID you will need to use get_the_category_by_ID()
.
You can retrieve also the ID by category name and you will use get_cat_ID( 'cat_name' )
.
Listing Product categories and subcategories with get_category()
(example):
Here it is an example of a function based on this thread, that will list all products categories and subcategories (everywhere):
function products_cats_subcats(){
$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 );
echo '<ul>';
foreach ($all_categories as $cat) {
if($cat->category_parent == 0) {
$category_id = $cat->term_id;
echo '<li><a href="'. get_term_link($cat->slug, 'product_cat') .'">'. $cat->name .'</a></li>';
$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 );
echo '<ol>';
if($sub_cats) {
foreach($sub_cats as $sub_category) {
echo '<li><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">' . $sub_category->name .'</a></li>';
}
}
echo '</ol>';
}
}
echo '</ul>';
}
To use it just put it where you want: <?php products_cats_subcats() ;?>
That will display all your categories and subcategories hierarchically ordered by Name, with the corresponding link for each category or subcategory.
Then you can also use get_term_by() to get the category name or slug:
$term = get_term_by('id', $term_id, 'product_cat', 'ARRAY_A');
$term['name']; //get the WC category name
$term['slug']; //get the WC category slug
Then now you will be able to build your own functions, to feet your needs…
Reference: