Skip to content
WooCommerce

Request

Get the id of the top level category for a product no matter what it’s depth in the category tree.

Required Plugins

Code

function get_product_top_level_category ( $product_id ) {
 
        $product_terms            =  get_the_terms ( $product_id, 'product_cat' );
        $product_category         =  $product_terms[0]->parent;
        $product_category_term    =  get_term ( $product_category, 'product_cat' );
        $product_category_parent  =  $product_category_term->parent;
        $product_top_category     =  $product_category_term->term_id;
 
        while ( $product_category_parent  !=  0 ) {
                $product_category_term    =  get_term ( $product_category_parent, 'product_cat' );
                $product_category_parent  =  $product_category_term->parent;
                $product_top_category     =  $product_category_term->term_id;
        }
 
        return $product_top_category;
}

Thinking

I tried a multitude of different built in WordPress and WooCommerce functions to get me to the top, but none of them actually did what I needed it to do which was return the id of the top-level category that a product might live in.

I needed this to work for any depth of categories, and a HUGE dependency is that it’s written to view the first category comes out of the get_the_terms call.

Disclaimer

Purrly Digital LLC cannot be held responsible for the functionality of this code. Please make sure you test it on a development site before adding the code to your production website. There is no support available for this (and other) code snippet(s) posted on this website. If you’d like Purrly Digital to do custom development to help with your custom implementation please send a contact request.

This Post Has One Comment

  1. thanks for your post. I am searching a code snippet to show woocommerce parent categories in list style. but I am tried to search it . if you have way to show list categories, please help me. thanks

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back To Top