One final death-blow to this horse (similar to the above answers) with a bit more refinement ... allowing you to also transform the list into a hierarchically-flat list with a depth
param.
Additionally, this function uses clone
to avoid modifying the original array.
/**
* Sort terms object list hierarchically or hierarchically-flat.
*/
function sort_terms_hierarchically( $terms, $parent_id = 0, $flat = FALSE, $depth = 0 ) {
$data = [];
foreach ( $terms as $term ) {
if ( $parent_id != $term->parent ) continue;
$data_term = clone $term;
$data_term->depth = $depth;
$children = sort_terms_hierarchically( $terms, $term->term_id, $flat, $depth + 1 );
if ( ! $flat ) $data_term->children = $children;
$data[] = $data_term;
if ( $flat ) foreach( $children as $child ) $data[] = $child;
}
return $data;
}
function sort_terms_hierarchically_flat( $terms, $parent_id = 0 ) {
return sort_terms_hierarchically( $terms, $parent_id, TRUE );
}
Usage is as follows:
$terms = get_terms( [
'taxonomy' => 'regions',
'hide_empty' => FALSE,
] );
$terms_sorted = sort_terms_hierarchically( $terms );
$terms_sorted_flat = sort_terms_hierarchically_flat( $terms );