I am trying to sort through a multi level hierarchy in a custom taxonomy.
I have custom taxonomy's with multiple sub taxonomy's. Eg:
Level1
-Level2
--Level3
ect
At the moment I can use get_term_children()
to return the children for a top level taxonomy but this doesn't tell me anything about there position in the hierarchy.
I am trying to sort through a multi level hierarchy in a custom taxonomy.
I have custom taxonomy's with multiple sub taxonomy's. Eg:
Level1
-Level2
--Level3
ect
At the moment I can use get_term_children()
to return the children for a top level taxonomy but this doesn't tell me anything about there position in the hierarchy.
2 Answers
Reset to default 1You'll probably have to run a cycle using get_terms() paired with the 'parent' attribute.
$args = array( 'parent' => 0 );
$parents = get_terms( array( 'custom-tax' ), $args );
foreach ( $parents as $parent ) {
echo $parent->name;
$args['parent'] = $parent->term_id;
if ( $children = get_terms( array( 'custom-tax' ), $args ) ) {
foreach ( $children as $child ) {
echo $child->name;
}
}
}
You may be able to rewrite the "if ( $children..." into a while loop if you need more recursion than that.
You can recursively create a hierarchical structure using this function:
function sort_hierarchical(array &$cats, array &$into, $parent_id = 0){
foreach ($cats as $i => $cat) {
if ($cat->parent == $parent_id) {
$into[$cat->term_id] = $cat;
unset($cats[$i]);
}
}
foreach ($into as $top_cat) {
$top_cat->children = array();
sort_hierarchical($cats, $top_cat->children, $top_cat->term_id);
}
}
And use it like this:
$terms = get_terms(array('taxonomy' => 'category', 'hide_empty' => false));
$cats = array();
sort_hierarchical($terms,$cats) ;