Last active
December 22, 2015 10:19
-
-
Save pospi/6457915 to your computer and use it in GitHub Desktop.
Wordpress helper method for efficiently organising a hierarchical taxonomy into a hierarchical data structure. Similar code could be used to organise any hierarchical dataset.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* 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 Array $into result array to put them in | |
* @param integer $parentId the current parent ID to put them in | |
*/ | |
function sortHierarchicalTaxonomy(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(); | |
sortHierarchicalTaxonomy($cats, $topCat->children, $topCat->term_id); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment