这看起来应该很容易,但我无法做到,也找不到任何关于它的帖子.
我可以显示与产品或*类别相关的所有类别,但您如何仅回显产品的最低/最深类别?
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;