我配置了以下产品类别结构:
我想显示基于此行为的类别/子类别列表:
我已经尝试了很多不同的代码并得到了一些结果,但没有一个不排除当前子类别。
非常感谢您的帮助!
答案 0 :(得分:0)
感谢这两个帖子:this one 和 this one 我设法得到了结果!我还添加了一个代码来显示子类别时的父类别。
$current_category = get_queried_object();
/** PARENTS **/
/** Get Category ID of current page **/
$current_category_id = $current_category->term_id;
/** Get Array of Category Parents **/
$parent_cat = get_ancestors($current_category_id, 'product_cat');
/** Get infos of first Parent **/
$parent_cat_term = get_term( $parent_cat[0], 'product_cat' );
$parent_cat_name = $parent_cat_term->name;
$parent_cat_id = $parent_cat_term->term_id;
/** CHILD **/
if ( $current_category->parent != 0 ) {
$child_cat_ids = get_term_children( $current_category->parent, 'product_cat' );
/** DISPLAY PARENT **/
if (!empty($parent_cat_id))/** Avoid error when no parent **/{
echo '<a href="' . get_term_link( $parent_cat_id, 'product_cat' ) . '">' . $parent_cat_name . '</a>';
}
/** DISPLAY CHILDS **/
foreach ( $child_cat_ids as $child_cat_id ) {
if( $child_cat_id != $current_category->term_id ) {
$child_cat_term = get_term_by( 'id', $child_cat_id, 'product_cat' );
echo '<a href="' . get_term_link( $child_cat_id, 'product_cat' ) . '">' . $child_cat_term->name . '</a>';
}
}
}