How to get the top most term (top ancestor) of a custom taxonomy child term?

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

Suppose the following term hierarchy:

Read More
    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;

        }

}

Related posts

Leave a Reply

1 comment