我正在尝试将帖子自定义分类法拉入页面。类别有子类别,我正在努力解决如何以层级方式列出子类别。目前我使用的是下面显示的类别,但它们都是混乱的。
$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; ?>我尝试了许多选项,但它们似乎都显示了该自定义分类中的所有类别和子类别,而不仅仅是与本文相关的类别。
任何帮助或指导都将不胜感激。
发布于 2021-04-10 01:05:42
您应该获取父分类法,然后对于每个父分类法,使用循环(Foreach)获取它们的子代。
1-通过以下查询查找父分类:
$args = array (
'taxonomy' => 'listing_category',
'parent' => 0,
'hide_empty' => false
);
$allTaxParent = get_categories($args);2-现在创建一个从parent获取子代的函数:
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>';
}https://stackoverflow.com/questions/67023469
复制相似问题