Skip to content

Instantly share code, notes, and snippets.

@tripflex
Last active October 23, 2018 15:19
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 tripflex/631610f46350edf4b84d88dad75e6517 to your computer and use it in GitHub Desktop.
Save tripflex/631610f46350edf4b84d88dad75e6517 to your computer and use it in GitHub Desktop.
Recursively get WordPress taxonomy and its children, adding to term object as sub-array
<?php
if( ! function_exists( 'smyles_get_taxonomy_hierarchy' ) ){
/**
* Recursively get taxonomy and its children
*
* @param string $taxonomy
* @param int $parent Parent term ID (0 for top level)
* @param array $args Array of arguments to pass to get_terms (to override default)
*
* @return array
*/
function smyles_get_taxonomy_hierarchy( $taxonomy, $parent = 0, $args = array( 'hide_empty' => false ) ) {
$defaults = array(
'parent' => $parent,
'hide_empty' => false
);
$r = wp_parse_args( $args, $defaults );
// get all direct decendants of the $parent
$terms = get_terms( $taxonomy, $r );
// 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 decendants of $parent, and gather their children
foreach ( $terms as $term ) {
// recurse to get the direct decendants of "this" term
$term->children = smyles_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;
}
}
@tripflex
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment