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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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 ) . '" rel="nofollow noreferrer noopener">' . $term->name . '</a></li>';
    }
    $output .= '</ul>';

    return $output;
}

Method 2

Since 3.1.0, get_ancestors() is available. It returns an array of ancestors from lowest to highest in the hierarchy.

Method 3

Here is a simple function that will get you the top most parent term of any given term:

function get_term_top_most_parent( $term_id, $taxonomy ) {
    $parent  = get_term_by( 'id', $term_id, $taxonomy );
    while ( $parent->parent != 0 ){
        $parent  = get_term_by( 'id', $parent->parent, $taxonomy );
    }
    return $parent;
}

Once you have this function you can just loop over the results returned by wp_get_object_terms:

$terms =  wp_get_object_terms( $post->ID, 'taxonomy' );
$top_parent_terms = array();
foreach ( $terms as $term ) {

    //Get top level parent
    $top_parent = get_term_top_most_parent( $term->ID, 'taxomony' );

    //Check if you have it in your array to only add it once
    if ( !in_array( $top_parent->ID, $top_parent_terms ) ) {
        $top_parent_terms[] = $top_parent;
    }
}

Method 4

/**
 * Get top level term
 */
function get_top_level_term($term,$taxonomy){
    if($term->parent==0) return $term;
    $parent = get_term( $term->parent,$taxonomy);
    return get_top_level_term( $parent , $taxonomy );
}

Method 5

I had the same problem and I solved easily. Check this out:

Define $taxonomy. It can be the slug of the taxonomy you want to get the data.
After doing this, you can simply do this:

<?php
    $postterms = wp_get_post_terms($post->ID, $taxonomy);   // get post terms
    $parentId = $postterms[0]->parent;                      // get parent term ID
    $parentObj = get_term_by('id', $parentId, $taxonomy);   // get parent object 
?>

Now you got something like this:

object(stdClass)#98 (11) {
  ["term_id"]=>
  int(3)
  ["name"]=>
  string(8) "Esportes"
  ["slug"]=>
  string(8) "esportes"
  ["term_group"]=>
  int(0)
  ["term_taxonomy_id"]=>
  int(3)
  ["taxonomy"]=>
  string(17) "noticiaseditorias"
  ["description"]=>
  string(0) ""
  ["parent"]=>
  int(0)
  ["count"]=>
  int(4)
  ["object_id"]=>
  int(123)
  ["filter"]=>
  string(3) "raw"
}

And you can use $parentObj to get slug, name, id, whatever. Just by using $parentObj->slug or $parentObj->name as exemple.

Method 6

Easiest way:

$rootId = end( get_ancestors( $term_id, 'my_taxonomy' ) );
$root = get_term( $rootId, 'my_taxonomy' );
echo $root->name;

Method 7

Maybe this helps: get_ancestors( $object_id, $object_type );

codex.wordpress.org

Method 8

Try this!

function get_term_top_most_parent( $term_id, $taxonomy ) {
    $ancestors = get_ancestors( $term_id, $taxonomy );

    if(!empty($ancestors)){
        $parentID = end( $ancestors );
    }else{
        $parentID = $term_id;
    }
    return $parentID;
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x