Get last child from a product category

1

Hello, good afternoon.

I need to get the last child of a category within a product loop:

Categoria
-categoria filho
--categoria ultimo filho

This gives me always the Father, that is, 'Category':

   <?php

        $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 = 'sem parent';
            }

            $attr = $top_term->slug;
        } else {
            $attr = 'sem categoria';
        }
?>
    
asked by anonymous 05.03.2015 / 20:34

1 answer

2

wp_get_object_terms() is your friend here. Once you have the post ID, call wp_get_object_terms($post_ID) , and it will return an array containing all categories associated with it, and making reference to who's parent. So you can figure out which one is the last one.

Bonus : This method takes more than one parameter, so you can use it with custom taxonomies as well as filter the desired return. Read about it in the Codex .

    
12.05.2015 / 17:00