Last active
October 23, 2018 15:19
-
-
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
This file contains 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 | |
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Original code base based off of https://www.daggerhart.com/wordpress-get-taxonomy-hierarchy-including-children/