循环输出(echo?)父自定义分类法的直接子项

Output (echo?) direct children of parent custom taxonomy in a loop

我试图在某种循环中仅输出第一个子级(不是父级或孙级)自定义分类法,因此我可以向其添加自定义字段/缩略图。

我创建了一个名为 'product-type'

的分层自定义 post 类型

它有几个级别的自定义分类法。

1 级 - 零食

2 级 - 巧克力(本例中只显示 1)

3 级 - 牛奶巧克力、黑巧克力..等等。

在父分类页面上,我已经能够使用以下代码成功列出所有现有的 2 级分类:

<?php 
$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); 
if ($term->parent == 0) {  
wp_list_categories('taxonomy=product-type&depth=1&show_count=0
&title_li=&child_of=' . $term->term_id);
} else {
wp_list_categories('taxonomy=product-type&show_count=0
&title_li=&child_of=' . $term->parent); 
}
?>

输出看起来像这样:

<li class="cat-item cat-item-7">
<a href="..." title="...">Chocolates</a> (14)
</li>

我的问题是,我如何编辑上面的 php 代码,以便我可以在某种循环中仅输出(回声?)第一个子级(不是父级或孙级)分类法可以插入 div 或自定义字段吗?

试试这件尺码。

https://codex.wordpress.org/Function_Reference/get_terms

<?php 
$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); 
if ($term->parent == 0) {  
    $terms = get_terms( 'product-type', 'child_of='.$term->term_id );
} else {
    $terms = get_terms( 'product-type', 'child_of='.$term->parent );
}
foreach($terms as $term) {
    // Your custom HTML
}
?>