WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

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;



            else { 

                    $parent = $child->term_id; 


            return $parent;


share|improve this question
up vote 3 down vote accepted

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

share|improve this answer
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 '12 at 5:47
If you check properly, it returns an array of ancestors from lowest to highest in the hierarchy. – Joshua Abenazer Aug 28 '12 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 '12 at 6:10
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 '12 at 6:16

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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