Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
470 views
in Technique[技术] by (71.8m points)

php - Using get_the_terms() doesn't return child terms of a specific parent category applied to a WooCommerce product

After numerous attempts and about 50 articles I am reaching the conclusion this is not possible, unless there is a wizard out there willing to tear me a page out of their spell book.

When on a product page, I wish to grab the current product ID and pass this to a get_the_terms() function, also providing the taxonomy 'product_cat' and finally specify the parent category.

Within the parent category we are passing, only one child category is selected. So this should only return one term.

I wish to do something like this:

$terms = get_the_terms( the_ID(), 'product_cat', array( 'parent' => 84 ) );
foreach ($terms as $term) {
    $termID = $term->term_id;
    $name   = $term->name;
    $slug   = $term->slug;

    echo $name;
}

However this returns numerous results, I tried a bunch of other similar queries but this would easily be the most beautiful, if anyone can shed some light, that would be great!

question from:https://stackoverflow.com/questions/65907557/using-get-the-terms-doesnt-return-child-terms-of-a-specific-parent-category-a

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Simply get_the_terms() doesn't allow additional arguments, instead use wp_get_post_terms() and also you should use get_the_ID() instead of the_ID() like

$terms = wp_get_post_terms( get_the_id(), 'product_cat', array( 'parent' => 84 ) );

It should better work now.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...