Created
July 18, 2016 20:17
-
-
Save tripflex/38df9846b06b8a2dca9f4bf1867e5be7 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/ )
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 | |
/** | |
* 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; | |
} |
Just add 'hide_empty' => false
to line 18, like this:
$terms = get_terms( $taxonomy, array('parent' => $parent, 'hide_empty' => false) );
nice!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, This is interesting. Just wanted to use this with
'hide_empty' => false,
So empty terms will also be part of of array.
One major thing if it is possible depth level of taxonomy? For example if i can show like tree. Right now we can't get depth level.
I need something like below tree
Level 0
-- Level 1
--- Level 2
---- Level 3
--- Level 2
---- Level 3
---- Level 3
-- Level 1
--- Level 2
Basically we have term "location" and wanted to show in checkbox but with depth level so we can style it.
Is it possible?
Thanks in adavance