How to get the top level parent term related to the current archive page?

I have a custom taxonomy called product_category that holds products. How does one get the top-level parent term with a list of children terms?

I know how to get a global list of top-level terms using get_terms() and passing in '0' as the parent, but I only want the one that it related to the current archive page.

Read More

Example:

Magazines
–Glossy
—-Fashion
Books
–Hardcover
—-Adventure

If I happened to be on the Fashion archive, I only want to get Magazines with a list of child terms, not Books.

Related posts

Leave a Reply

3 comments

  1. I think I figured it out. I ended up with the following:

    $term_id = get_queried_object()->term_id; //Get ID of current term
    $ancestors = get_ancestors( $term_id, 'product_category' ); // Get a list of ancestors
    $ancestors = array_reverse($ancestors); //Reverse the array to put the top level ancestor first
    $ancestors[0] ? $top_term_id = $ancestors[0] : $top_term_id = $term_id; //Check if there is an ancestor, else use id of current term
    $term = get_term( $top_term_id, 'product_category' ); //Get the term
    echo $term->name; // Echo name of top level ancestor
    

    Perhaps there is a better way to do this, but this seems to work fine.

  2. I like that solution cbi. I can’t believe I’ve had such a difficulty getting this information when making a custom hierarchical taxonomy term archive.

  3. <?php
    
      $terms = get_the_terms( $post->ID, 'categories' );
      if ( !empty( $terms ) ){
        // get the first term
        $term = array_shift( $terms );
        $term_id = $term->term_id;
      }
    
      $ancestors = get_ancestors( $term_id, 'categories' ); // Get a list of ancestors
      $ancestors = array_reverse($ancestors); //Reverse the array to put the top level ancestor first
      $ancestors[0] ? $top_term_id = $ancestors[0] : $top_term_id = $term_id; //Check if there is an ancestor, else use id of current term
      $term = get_term( $top_term_id, 'categories' ); //Get the term
      $top_term_id = $term->term_id;
      echo $top_term_id; // Echo name of top level ancestor
    
    ?>