尝试创建显示当前产品类别的兄弟级和第一级子级的函数。兄弟姐妹的孩子和孩子们的孩子也是如此。
类别可以达到4层深度,我需要列表来改变它所显示的内容取决于当前页面。
示例:
2
我发现有几个帖子解释了显示兄弟姐妹的原因,或者是第一级的孩子。但我试图将两者结合起来,但没有成功:
Get a list of siblings term ids from current product category in WooCommerce
Display current category first then child categories in WooCommerce
有什么想法吗?任何能把我引向正确方向的东西都会有帮助。
发布于 2021-12-10 21:45:08
经过多次尝试和错误之后,我终于明白了:
function wc_cat_menu() {
$queried_object = get_queried_object();
$taxonomy = 'product_cat';
$sibling_terms = get_terms( array(
'taxonomy' => $taxonomy,
'hide_empty' => false,
'parent' => $queried_object->parent
) );
echo '<ul>';
foreach( $sibling_terms as $sibling ) {
if ( $sibling->parent > 0 ) {
$sibling_id = $sibling->term_id;
$siblingChildren = get_terms( $taxonomy, array(
'parent' => $sibling_id,
'hide_empty' => false
) );
echo '<li><a href="' . get_term_link( $sibling ) . '">' . $sibling->name . '<span> (' . $sibling->count . ')</span></a>';
if( $siblingChildren ) {
echo '<ul>';
foreach ( $siblingChildren as $child ) {
echo '<li><a href="' . get_term_link( $child, $taxonomy ) . '">' . $child->name . '<span> (' . $child->count . ')</span></a></li>';
}
echo '</ul>';
}
echo '</li>';
}
}
echo '</ul>';
}
在这个过程中学到了很多东西!可能有一个非常有效的方法来实现这一点,任何建议都欢迎。
https://stackoverflow.com/questions/70305795
复制相似问题