Skip to content

Instantly share code, notes, and snippets.

@Inzman
Created October 17, 2019 13:37
Show Gist options
  • Save Inzman/b41a53072ec41eda091cca7ab7327ada to your computer and use it in GitHub Desktop.
Save Inzman/b41a53072ec41eda091cca7ab7327ada to your computer and use it in GitHub Desktop.
Hierarchical terms list
/**
* Recursively sort an array of taxonomy terms hierarchically. Child categories will be
* placed under a 'children' member of their parent term.
* @param Array $cats taxonomy term objects to sort
* @param integer $parentId the current parent ID to put them in
*/
function sort_terms_hierarchicaly(Array $cats, $parentId = 0)
{
$into = [];
foreach ($cats as $i => $cat) {
if ($cat->parent == $parentId) {
$cat->children = sort_terms_hierarchicaly($cats, $cat->term_id);
$into[$cat->term_id] = $cat;
}
}
return $into;
}
$sorted_terms = sort_terms_hierarchicaly($terms);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment