Skip to content

Instantly share code, notes, and snippets.

@adnan360
Last active November 7, 2018 05:27
Show Gist options
  • Save adnan360/74b54dc4e019b6f5b7aa0707bea9848a to your computer and use it in GitHub Desktop.
Save adnan360/74b54dc4e019b6f5b7aa0707bea9848a to your computer and use it in GitHub Desktop.
Get Yoast SEO primary category
<?php
/**
* Gets Yoast SEO primary category.
*
* @param int $post_id ID of the product to get category of.
* @return string
*/
public function get_primary_cat( $post_id ) {
$cat_name = '';
if ( class_exists( 'WPSEO_Primary_Term' ) ) {
$primary_cat_id = get_post_meta( $post_id, '_yoast_wpseo_primary_product_cat', true );
if ( $primary_cat_id ) {
$product_cat = get_term( $primary_cat_id, 'product_cat' );
if ( isset( $product_cat->name ) ) {
$cat_name = $product_cat->name;
}
}
}
return $cat_name;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment