I am trying to sort through a multi level hierarchy in a custom taxonomy.

I have custom taxonomy's with multiple sub taxonomy's. Eg:



At the moment I can use get_term_children() to return the children for a top level taxonomy but this doesn't tell me anything about there position in the hierarchy.

2 Answers 2


You'll probably have to run a cycle using get_terms() paired with the 'parent' attribute.

$args = array( 'parent' => 0 );
$parents = get_terms( array( 'custom-tax' ), $args );
foreach ( $parents as $parent ) {
    echo $parent->name;
    $args['parent'] = $parent->term_id;
    if ( $children = get_terms( array( 'custom-tax' ), $args ) ) {
        foreach ( $children as $child ) {
            echo $child->name;

You may be able to rewrite the "if ( $children..." into a while loop if you need more recursion than that.

  • That code only works for 2 levels, though I understand though how you could convert it across to multiple. I was really looking to see if wordpress stored any data on the hierarchy. Jan 30, 2014 at 17:19
  • It does, but I believe it does it through the 'parent' attribute, not a numerical representation of what level the term lives at.
    – socki03
    Jan 30, 2014 at 17:23

You can recursively create a hierarchical structure using this function:

function sort_hierarchical(array &$cats, array &$into, $parent_id = 0){

    foreach ($cats as $i => $cat) {
        if ($cat->parent == $parent_id) {
            $into[$cat->term_id] = $cat;

    foreach ($into as $top_cat) {
        $top_cat->children = array();
        sort_hierarchical($cats, $top_cat->children, $top_cat->term_id);

And use it like this:

$terms = get_terms(array('taxonomy' => 'category', 'hide_empty' => false));
$cats = array();
sort_hierarchical($terms,$cats) ;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.