这看起来应该很容易做到,但我没能做到,也找不到任何关于它的帖子。
我可以显示与产品相关的所有类别,或顶级类别,但您如何只显示产品的最低/最深类别?
Cat-A [x]
Cat-B [x]
Cat-C [x]
Cat-D [ ]
Cat-E [ ]
Cat-F [ ]
Cat-G [ ]
Cat-H [ ]
如果这个例子是产品的祖先,我只想打印“Cat-C”。
但我不想像其他解决方案那样手动设置类别级别,我希望它始终打印最低的子项,无论是存档页面上的产品,还是单个产品页面。
知道如何/应该如何做到这一点吗?
最佳答案
尝试这样的事情:
// get all product cats for the current post
$categories = get_the_terms( get_the_ID(), 'product_cat' );
// wrapper to hide any errors from top level categories or products without category
if ( $categories && ! is_wp_error( $category ) ) :
// loop through each cat
foreach($categories as $category) :
// get the children (if any) of the current cat
$children = get_categories( array ('taxonomy' => 'product_cat', 'parent' => $category->term_id ));
if ( count($children) == 0 ) {
// if no children, then echo the category name.
echo $category->name;
}
endforeach;
endif;
关于php - 在 woocommerce 中显示当前产品的最深子类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25896981/