根据需要,我使用了几个递归函数。两者都需要术语列表、起始父id和起始(通常为空)数组来放置结果列表。
第一版
$terms = [a list of terms objects, use get_terms of whatever]
$ordered_terms = array(); // here you\'ll find your ordered terms, from root to final child
function list_terms_by_parent($parent_id = 0, &$terms, &$ordered_terms){
$root_parent = $parent_id;
foreach($terms as $index => $term){
if($term->parent == (int) $parent_id){
$ordered_terms[$term->term_id] = $term;
$root_parent = $term->term_id;
unset($terms[$index]);
}
}
if(!empty($terms)) list_terms_by_parent($root_parent, $terms, $ordered_terms);
}
第二版
$term_ids = [should be a list of ids in the form of child_id => parent_id]
// a fast way to get that kind of list is to use WP_Term_query, example:
//$terms_query = new WP_Term_Query(array(
// \'taxonomy\' => \'product_categories\'
// ,\'object_ids\' => $post->ID
// ,\'hide_empty\' => false
// ,\'fields\' => \'id=>parent\'
//));
$ordered_terms = array(); // here you\'ll find your ordered terms, from root to final child
function list_term_ids_by_parent($parent_id = 0, &$term_ids, &$ordered_terms){
$child_id = array_search($parent_id, $term_ids);
if($child_id){
$ordered_terms[] = $child_id;
unset($term_ids[$child_id]);
}
if(!empty($term_ids)) order_terms($child_id, $term_ids, $ordered_terms);
}
第三版
这不是我的,我在某处找到的,可能是在这里或stackoverflow。这在输出上有点不同,因为它将生成一个级联术语列表,只有一个根,它有一个children属性,它将包含下一个术语及其children属性,依此类推。。
//$ordered\\u terms应该是如上所述的空数组
function sort_terms_hierarchically(&$terms, &$ordered_terms, $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);
}
}