Get product main category woocommerce wordpress

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;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s