How to get primary category set via Yoast seo plugin in WordPress

The Yoast SEO plugin now has a dedicated function — yoast_get_primary_term_id() — for getting the primary term's ID:

$primary_term_id = yoast_get_primary_term_id( 'taxonomy_slug', $post_id_or_object );

You can then use get_term() to get the WP_Term object:

// Will return `false` if no primary term has been set
$primary_term_id = yoast_get_primary_term_id( 'taxonomy_slug', $post_id_or_object );

if ( $primary_term_id ) {
    /** @var WP_Term $primary_term */
    $primary_term = get_term( $primary_term_id );
}

For those scenarios where you just need the term's name, you can use yoast_get_primary_term():

// Will return an empty string if no primary term has been set
$primary_term_name = yoast_get_primary_term( 'taxonomy_slug', $post_id_or_object );

I could not get the accepted answer to work. I modified this to fit my needs

$cat_name = ''; // I have this set in some shortcodes

if (!isset($cat_name) || $cat_name == '') {

  if ( class_exists('WPSEO_Primary_Term') ) {

    // Show the post's 'Primary' category, if this Yoast feature is available, & one is set. category can be replaced with custom terms

    $wpseo_primary_term = new WPSEO_Primary_Term( 'category', get_the_id() );

    $wpseo_primary_term = $wpseo_primary_term->get_primary_term();
    $term               = get_term( $wpseo_primary_term );

    if (is_wp_error($term)) {
        $categories = get_the_terms(get_the_ID(), 'category');
        $cat_name = $categories[0]->name;
    } else {
        $cat_name = $term->name;
    }

  } else {
    $categories = get_the_terms(get_the_ID(), 'category');
    $cat_name = $categories[0]->name;
  }
}

echo $cat_name;

I have edited a working example to be more self contained, I used it for custom taxonomy so used get_the_terms() instead of get_the_category(). This code has not been tested in its current state.


Hi you can get using postmeta table.

   $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->name)) 
           echo $primary_cat->name;
    }

Tags:

Wordpress