Skip to content

Instantly share code, notes, and snippets.

@tacensi
Created January 7, 2016 18:38
Show Gist options
  • Save tacensi/f8e022bebd215bd771f5 to your computer and use it in GitHub Desktop.
Save tacensi/f8e022bebd215bd771f5 to your computer and use it in GitHub Desktop.
Create an hierarchaly ordere array of terms
// Hierarchaly ordered array of terms
function sort_terms_hierarchicaly( Array &$cats, Array &$into, $parentId = 0 ) {
foreach ( $cats as $i => $cat ) {
if ( $cat->parent == $parentId ) {
$into[$cat->term_id] = $cat;
unset( $cats[$i] );
}
}
foreach ( $into as $topCat ) {
$topCat->children = array();
sort_terms_hierarchicaly( $cats, $topCat->children, $topCat->term_id );
}
}
/***
$categories = get_terms('my_taxonomy_name', array('hide_empty' => false));
$categoryHierarchy = array();
sort_terms_hierarchicaly($categories, $categoryHierarchy);
var_dump($categoryHierarchy);
***/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment