Answer the question
In order to leave comments, you need to log in
How to display the term_id of a child product category?
Good afternoon.
I am inside the product.
It is necessary to display the id of the current category (child, without parent)
There is a code:
<?php global $product; //Если не объявлен ранее. Не уверен в необходимости.
global $post;
$categories = get_the_terms( $post->ID, 'product_cat' );
foreach ($categories as $category) {
echo $category->term_id; //Может быть в нескольких категориях
}?>
Answer the question
In order to leave comments, you need to log in
Good afternoon.
$product_cats = wp_get_post_terms(get_the_ID(), 'product_cat');
if ($product_cats) {
$deepestTerm = false;
$maxDepth = -1;
foreach ($product_cats as $cat) {
$termDepth = count(get_ancestors($cat->term_id, 'product_cat'));
if ($termDepth > $maxDepth) {
$deepestTerm = $cat;
$maxDepth = $termDepth;
}
}
echo $deepestTerm->term_id;
}
Check which categories are listed for the product in the control panel. It often happens that they indicate the entire branch of the tree. Try to leave only the last category in the branch.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question