Return an array of the hierarchical taxonomy?

get_terms( array('taxonomy' => 'champ', 'hide_empty' => true)) returns the set of all taxonomy items in the same pile, even if it is hierarchical.

Array
(
 [5] => Object WP_Term
(
 [term_id] => 9
 [name] => Premier League
 [slug] = > %d0%bf%d1%80%d0%b5%d0%bc%d1%8c%d0%b5%d1%80-%d0%bb%d0%b8%d0%b3%d0%b0-%d1%80%d0%be%d1%81%d1%81%d0%b8%d1%8f
 [term_group] => 0
 [term_taxonomy_id] => 9
 [taxonomy] => champ
 [description] => 
 [parent] => 2
 [count] => 1
 [filter] => raw
)

 [6] => Object WP_Term
(
 [term_id] => 2
 [name] => Russia
 [slug] => %d1%80%d0%be%d1%81%d1%81%d0%b8%d1%8f
 [term_group] => 0
 [term_taxonomy_id] => 2
 [taxonomy] => champ
 [description] => 
 [parent] => 0
 [count] => 1
 [filter] => raw
)

 [9] => Object WP_Term
(
 [term_id] => 10
 [name] => CSKA
 [slug] => %d1%86%d1%81%d0%ba%d0%b0
 [term_group] => 0
 [term_taxonomy_id] => 10
 [taxonomy] => champ
 [description] => 
 [parent] => 9
 [count] => 1
 [filter] => raw
)

)


Can I return the elements of the hierarchical taxonomies as an associative array in which the descendant would be in the parent?
June 26th 19 at 13:59
1 answer
June 26th 19 at 14:01
Solution
get_taxonomy_hierarchy function( $taxonomy, $parent = 0 ) {
 $taxonomy = is_array( $taxonomy ) ? array_shift( $taxonomy ) : $taxonomy;
 $terms = get_terms( $taxonomy, array( 'parent' => $parent, 'hide_empty' => false ) );
 $children = array();
 foreach ( $terms as $term ){
 $term->children = get_taxonomy_hierarchy( $taxonomy, $term->term_id );
 $children[ $term->term_id ] = $term;
}
 return $children;
}

print_r(get_taxonomy_hierarchy('champ',0));

Find more questions by tags WordPress