Сортировка термов по иерархии

Функция get_terms() забирает термы из базы, но она не умеет формировать из них дерево в соответствии с иерархией, только указывает родительский терм.

Следующая функция формирует из полученных термов дерево:

[php]function sort_terms_hierarchicaly(Array &$terms, Array &$into, $parentId = 0) {

foreach ($terms as $i => $term) {
if ($term->parent == $parentId) {
$into[$term->term_id] = $term;
unset($terms[$i]);
}
}

foreach ($into as $topTerm) {
$topTerm->children = array();
sort_terms_hierarchicaly($terms, $topTerm->children, $topTerm->term_id);
}
}[/php]

Ее можно добавить в файл functions.php и далее использовать в любом месте темы, например таким образом:

[php]$flat_terms = get_terms( ‘simptomy’, array( ‘orderby’ => ‘name’, ‘hide_empty’ => true ) );
$terms = array(); sort_terms_hierarchicaly($flat_terms, $terms);
if ( ! empty ( $terms ) ) {
foreach( $terms as $term ) {
echo $term->name . ‘<br>’;
if ( ! empty( $term->children ) ) {
foreach ( $term->children as $term ) {
echo ‘- ‘ . $term->name . ‘<br>’;
}
}
}
}[/php]