我尝试在父/子类别模板(woocommerce)中显示父和子类别。 我使用下面的代码,它只是在父类别中显示子类别。
更新代码:
<?php
$counter = 0;
$term = get_queried_object();
$children = get_terms( $term->taxonomy, array(
'parent' => $term->term_id,
'hide_empty' => false
) );
$categories = [ $term ];
// If $children is an array just merge the "current" (parent) category with the children
if ( is_array( $children ) ) {
$categories = array_merge( $categories, $children );
}
foreach( $categories as $subcat ) {
echo '<ul><li><a href="' . esc_url(get_term_link($subcat, $subcat->taxonomy)) . '">' . $subcat->name . '</a></li></ul>';
}
?>
答案 0 :(得分:0)
在这种情况下,您要查询所有“子项”,在尝试创建包含所有已有数据的数组时,只需构造它。
<?php
$counter = 0;
$term = get_queried_object();
$children = get_terms( $term->taxonomy, array(
'parent' => $term->term_id,
'hide_empty' => false
) );
$categories = [ $term ];
// If $children is an array just merge the "current" (parent) category with the children
if ( is_array( $children ) ) {
$categories = array_merge( $categories, $children );
}
foreach( $categories as $subcat ) {
echo '<ul><li><a href="' . esc_url(get_term_link($subcat, $subcat->taxonomy)) . '">' . $subcat->name . '</a></li></ul>';
}
?>
如您在上面的示例中看到的那样,添加了一小段代码来代替将两个数组合并为一个数组。