Skip to content

Instantly share code, notes, and snippets.

@monkeymonk
Forked from tripflex/functions.php
Created September 23, 2021 09:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save monkeymonk/53822d65e2f48c869d601d409995da37 to your computer and use it in GitHub Desktop.
Save monkeymonk/53822d65e2f48c869d601d409995da37 to your computer and use it in GitHub Desktop.
WordPress Recursively get taxonomy hierarchy (courtesy of http://www.daggerhart.com/wordpress-get-taxonomy-hierarchy-including-children/ )
<?php
/**
* Recursively get taxonomy hierarchy
*
* @source http://www.daggerhart.com/wordpress-get-taxonomy-hierarchy-including-children/
* @param string $taxonomy
* @param int $parent - parent term id
*
* @return array
*/
function get_taxonomy_hierarchy( $taxonomy, $parent = 0 ) {
// only 1 taxonomy
$taxonomy = is_array( $taxonomy ) ? array_shift( $taxonomy ) : $taxonomy;
// get all direct decendents of the $parent
$terms = get_terms( $taxonomy, array('parent' => $parent) );
// prepare a new array. these are the children of $parent
// we'll ultimately copy all the $terms into this new array, but only after they
// find their own children
$children = array();
// go through all the direct decendents of $parent, and gather their children
foreach( $terms as $term ) {
// recurse to get the direct decendents of "this" term
$term->children = get_taxonomy_hierarchy( $taxonomy, $term->term_id );
// add the term to our new array
$children[ $term->term_id ] = $term;
}
// send the results back to the caller
return $children;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment