Get the the top-level parent of a custom taxonomy term

How would I get the top-level parent of a given term?

I am using wp_get_object_terms to get taxonomy terms on posts, but instead of showing all tagged terms, I only want to show tagged terms’ top-level parents.

So if these are my selected terms, I only want to show Breakfast, Lunch and Dinner.

x BREAKFAST
   x Cereal
   x Eggs
  LUNCH
     Hamburger
   x Pizza
  DINNER
     Fish
        Bass
      x Salmon
        Trout
     Lasagna

How can I do this?

8

Thanks to Ivaylo for this code, which was based on Bainternet’s answer.

The first function below, get_term_top_most_parent, accepts a term and taxonomy and returns the the term’s top-level parent (or the term itself, if it’s parentless); the second function (get_top_parents) works in the loop, and, given a taxonomy, returns an HTML list of the top-level parents of a post’s terms.

// Determine the top-most parent of a term
function get_term_top_most_parent( $term, $taxonomy ) {
    // Start from the current term
    $parent  = get_term( $term, $taxonomy );
    // Climb up the hierarchy until we reach a term with parent="0"
    while ( $parent->parent != '0' ) {
        $term_id = $parent->parent;
        $parent  = get_term( $term_id, $taxonomy);
    }
    return $parent;
}

Once you have the function above, you can loop over the results returned by wp_get_object_terms and display each term’s top parent:

function get_top_parents( $taxonomy ) {
    // get terms for current post
    $terms = wp_get_object_terms( get_the_ID(), $taxonomy );
    $top_parent_terms = array();

    foreach ( $terms as $term ) {
        //get top level parent
        $top_parent = get_term_top_most_parent( $term, $taxonomy );
        //check if you have it in your array to only add it once
        if ( !in_array( $top_parent, $top_parent_terms ) ) {
            $top_parent_terms[] = $top_parent;
        }
    }

    // build output (the HTML is up to you)
    $output="<ul>";
    foreach ( $top_parent_terms as $term ) {
          //Add every term
          $output .= '<li><a href="'. get_term_link( $term ) . '">' . $term->name . '</a></li>';
    }
    $output .= '</ul>';

    return $output;
}

Leave a Comment