这看起来应该很容易,但我还没能找到任何关于它的帖子。
我可以显示与产品或顶级类别相关联的所有类别,但您如何仅回显产品的最低/最深类别?
Cat-A [x]
Cat-B [x]
Cat-C [x]
Cat-D [ ]
Cat-E [ ]
Cat-F [ ]
Cat-G [ ]
Cat-H [ ]
如果这个例子是产品的祖先,那么我想打印的就是" Cat-C"。
但我不想像其他解决方案一样手动设置类别级别,我希望它始终打印最低的孩子,存档页面上的产品或单个产品页面。
知道如何/应该如何做到这一点?
答案 0 :(得分:5)
尝试类似:
// 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;
答案 1 :(得分:0)
我终于在https://wordpress.stackexchange.com/a/55921/59863找到了anwser我为woocommerce添加了适当的分类法,并在底部添加了foreach / echo以吐出名称。
//Get all terms associated with post in woocommerce's taxonomy 'product_cat'
$terms = get_the_terms( $post->ID, 'product_cat' );
//Get an array of their IDs
$term_ids = wp_list_pluck($terms,'term_id');
//Get array of parents - 0 is not a parent
$parents = array_filter(wp_list_pluck($terms,'parent'));
//Get array of IDs of terms which are not parents.
$term_ids_not_parents = array_diff($term_ids, $parents);
//Get corresponding term objects.
$terms_not_parents = array_intersect_key($terms, $term_ids_not_parents);
//Extract the name of the category from the array and post it.
foreach($terms_not_parents as $term_not_parent)
echo $term_not_parent->name;
此代码的唯一缺点是,如果产品只有1个类别,父值为0,它将会中断。我目前不需要这个功能,但是我会回来修复一个“if null,而不是”。