How to get main category by product id Yoast SEO

0
24

If in an online store written on the WooCommerce plugin, you need to get the main (main) category by product id (Yoast SEO), you can use the following code:

$cat = 0;
$taxonomy = 'product_cat';
$primary_cat_id=get_post_meta($product->id,'_yoast_wpseo_primary_' . $taxonomy, true);
if($primary_cat_id){
$primary_cat = get_term($primary_cat_id, $taxonomy);
if(isset($primary_cat->term_id)) {
// current category id
$cat = $primary_cat->term_id;
}
}

LEAVE A REPLY

Please enter your comment!
Please enter your name here