问题描述
我正在尝试将帖子自定义分类法拉入页面。类别有子类别,我正在努力练习如何以分层方式列出子类别。目前我正在使用下面的内容,它可以正确显示类别,但它们混杂在一起。
$terms = get_the_terms( $post_id,'listing_category' );
if ( $terms && ! is_wp_error( $terms ) ) :
$categories = array();
foreach ( $terms as $term ) {
$categories[] = $term->name;
}
$categories_list = join( ",",$categories ); ?>
<tr>
<td><strong>Categories: </strong></td>
<td><?PHP esc_html_e( $categories_list ) ?></td>
</tr>
<?PHP endif; ?>
我尝试了许多选项,但它们似乎都显示了该自定义分类法中的所有类别和子类别,而不仅仅是与此帖子相关的类别。
任何帮助或指导将不胜感激。
解决方法
你应该得到父母分类,然后为每个父母得到他们的孩子 带一个循环(foreach)。
1- 通过此查询查找父分类法:
$args = array (
'taxonomy' => 'listing_category','parent' => 0,'hide_empty' => false
);
$allTaxParent = get_categories($args);
2- 现在创建一个从父级获取子级的函数:
function getChildren( $termId=0,$taxonomy='category' ) {
$children = get_categories(
[
'child_of' => $termId,'taxonomy' => $taxonomy,'hide_empty' => false
]
);
return ($children);
}
3- 现在您有了分层方式的分类法:
foreach ( $allTaxParent as $tax ) {
$children = getChildren($tax->term_id,$tax->taxonomy);
echo $tax->name . '>';
foreach ($children as $child){
echo $child->name . '>';
}
echo '<br>';
}