一直在尝试这样做,但仍然没有运气。我试图列出按父子类别关系(层次视图)排序后分配给帖子的分类术语。
结构是这样的
Library = custom post type
Year = custom taxonomy assigned to "library"
- 2021 = parent term
-- April = child term
-- May = child term
-- June = child term
-- July = child term
所需输出为:
2021 4月、5月、6月、7月
我试过:
$terms = get_the_terms( $post->ID, \'document_year\' );
if ( $terms && ! is_wp_error( $terms ) ) :
$output = array();
foreach ( $terms as $term ) {
$output[] = $term->name;
}
echo \'<span>\' . implode ( \', \', $output ) . \'</span>\';
endif;
但这会输出术语的字母顺序。
与此相同:
echo ( get_the_term_list( $post->ID, \'category\', \'\', \' / \') );
有什么帮助吗?
SO网友:Baikare Sandeep
如果您需要建立术语的实际结构,这可能是一种有用的方法:
/**
* Recursively sort an array of taxonomy terms hierarchically. Child categories will be
* placed under a \'children\' member of their parent term.
* @param Array $cats taxonomy term objects to sort
* @param Array $into result array to put them in
* @param integer $parentId the current parent ID to put them in
*/
function sort_terms_hierarchically(Array &$cats, Array &$into, $parentId = 0)
{
foreach ($cats as $i => $cat) {
if ($cat->parent == $parentId) {
$into[$cat->term_id] = $cat;
unset($cats[$i]);
}
}
foreach ($into as $topCat) {
$topCat->children = array();
sort_terms_hierarchically($cats, $topCat->children, $topCat->term_id);
}
}
用法如下:
$categories = get_terms(\'my_taxonomy_name\', array(\'hide_empty\' => false));
$categoryHierarchy = array();
sort_terms_hierarchically($categories, $categoryHierarchy);
var_dump($categoryHierarchy);