1

I need to get the topmost term (top level ancestor) of a taxonomy term.

Suppose the following term hierarchy:

    North America
        United States
            New York
                New York City
    South America
         Mexico

I need to get the ID of "North America" term if I know the ID of "New York"

I'm using an adapted function found on stackexchange and a few other places after searching Google.

However, while using this function in my theme, the while loop turns out in a infinite loop for some reason, even if the $term_id and $taxonomy supplied are correct. Putting Wordpress in debug mode didn't help me to trace the issue. If I remove the while loop in the function, Wordpress restores to function properly (otherwise it hangs while outputting an infinite loop). However, I don't really how else I can get the topmost parent of a taxonomy term otherwise.

function get_term_top_most_parent( $term_id, $taxonomy ) {

        $child = get_term_by( 'id', $term_id, $taxonomy );

        if ( $child ) {

            $parent = get_term_by( 'id', $child->term_id, $taxonomy );
            $parent = $parent->parent;

            if ( $parent ) {

                while ( $parent != 0 ) :

                    $parent = get_term_by( 'id', $parent, $taxonomy );
                    $parent = $parent->parent;

                endwhile;

            }

            else { 

                    $parent = $child->term_id; 

            }

            return $parent;

        }

}

1 Answer 1

6

I guess this function is what you are looking for -> get_ancestors()

4
  • get_ancestors() afaik will return an array of terms if the child term is associated with more than one parent term; and there's no way to know which is the topmost in a hierarchy tree, which is what I want... thanks
    – unfulvio
    Aug 28, 2012 at 5:47
  • If you check properly, it returns an array of ancestors from lowest to highest in the hierarchy. Aug 28, 2012 at 6:01
  • oh cool, so I only need to fetch the 1st one? didn't realize it was ordered, thanks, I will check in a minute
    – unfulvio
    Aug 28, 2012 at 6:10
  • 1
    thanks indeed - it worked; I used reset($array) to get the 1st element of the get_ancestors() array, that's exactly what I needed
    – unfulvio
    Aug 28, 2012 at 6:16

Your Answer

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

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