B
B
Boris Belov2017-08-03 11:11:02
WordPress
Boris Belov, 2017-08-03 11:11:02

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; //Может быть в нескольких категориях
}?>

But it displays both the parent and child in which the product is located. And it is necessary ONLY child.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Yanchevsky, 2017-08-03
@iborisbelov

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;
}

W
WordPress WooCommerce, 2017-08-03
@maxxannik

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 question

Ask a Question

731 491 924 answers to any question