Get last child of a product category

Asked

Viewed 77 times

1

Everybody, good afternoon, everybody.

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

Categoria
-categoria filho
--categoria ultimo filho

It always gives me the Father, ie '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';
        }
?>
  • André Ribeiro, help awe, man.

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 the categories associated with it, and referencing who is the parent of whom. So you can figure out which is the last of them.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.