Getting the first parent of a hierarchical term

How get avô this hierarqui category:

avô
-mae
--filho

It always give me the last child :

<?php 

    $product_cats = wp_get_post_terms( get_the_ID(), 'product_cat' );

    $single_cat = array_shift( $product_cats ); 

    echo $single_cat->slug;

?>

Result: filho

Must obtain the category avô

UPDATE:

$product_cats return:

Array
(
    [0] => stdClass Object
        (
            [term_id] => 16
            [name] => Display
            [slug] => filho
            [term_group] => 0
            [term_taxonomy_id] => 16
            [taxonomy] => product_cat
            [description] => 
            [parent] => 7
            [count] => 2
            [filter] => raw
        )

)

Solutions Collecting From Web of "Getting the first parent of a hierarchical term"

Since you are in a Single Post you’ll need to first get the categories then use get_ancestors() to display the hierarchy.

$product_cats   = wp_get_post_terms( get_the_ID(), 'product_cat' );

if( ! empty( $product_cats ) ) {

    $single_cat     = array_shift( $product_cats );

    $product_ancs   = get_ancestors( $single_cat->term_id, 'product_cat' );

    if( ! empty( $product_ancs ) ) {

        $top_level_cat  = array_shift( array_reverse( $product_ancs ) );

        $single_cat     = get_term( $top_level_cat, 'product_cat' );
    }

    echo $single_cat->slug;
}

The above example runs some error checking if there are no categories checked or if the term attached has no parents. First we get all the Post Terms and use only 1 as the basis to get all its ancestors. If it has a parent or grandparent, it will be at the end of our $product_ancs array. Let’s look at the example given in The Codex:

  • Books (6)
    • Fiction (23)
      • Mystery (208)

<?php get_ancestors( 208, 'category' ); ?> Returns the following array:

Array
(
    [0] => 23
    [1] => 6
)

With the top level being at the end of the array which is way we take advantage of array_reverse().


A secondary method would be to use a loop and go through each term 1 by 1 until you reach the top. Every parent shouldn’t have a parent ( $top_term->parent will be 0 -> false -> empty ) so we can look for that in our loop:

 $product_cats = wp_get_post_terms( get_the_ID(), 'product_cat' );

 $single_cat = array_shift( $product_cats );

 if( ! empty( $product_cats ) ) {

        $single_cat = array_shift( $product_cats );

        $top_term = $single_cat;

        if( $top_term->parent > 0 ) {

            while( $top_term->parent > 0 ) {

                $top_term = get_term( $top_term->parent, 'product_cat' );

            }

        } else {

           $attr = 'no_parent';

        }

        $attr = $top_term->slug;

    } else {

        $attr = 'empty_categories';

    }

Once the while loop returns false ( reaches a parent of 0 ) we know we’ve hit the top of our hierarchy.