How to get main category by product id Yoast SEO

0
634

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


Notice: Function amp_has_paired_endpoint was called incorrectly. Function called while AMP is disabled via `amp_is_enabled` filter. The service ID "paired_routing" is not recognized and cannot be retrieved. Please see Debugging in WordPress for more information. (This message was added in version 2.1.1.) in /www/wwwroot/offgalaxy.com/wp-includes/functions.php on line 6085

Notice: Function amp_has_paired_endpoint was called incorrectly. Function called while AMP is disabled via `amp_is_enabled` filter. The service ID "paired_routing" is not recognized and cannot be retrieved. Please see Debugging in WordPress for more information. (This message was added in version 2.1.1.) in /www/wwwroot/offgalaxy.com/wp-includes/functions.php on line 6085