Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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;

        }

}
share|improve this question

1 Answer 1

up vote 2 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 –  nekojira 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 –  nekojira Aug 28 '12 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 –  nekojira Aug 28 '12 at 6:16

Your Answer

 
discard

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.