Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

wordpress

I have used a Yoast seo plugin and set primary category for product. But in front I cannot get primary category name.

like image 577
user1924744 Avatar asked Aug 06 '16 04:08

user1924744


People also ask

How do you get primary category Yoast?

With Yoast SEO, you can easily select the primary category when you are editing a post. Go to the Categories setting in the sidebar of the post editing screen. Click on the dropdown menu under Select the primary category.

How do I find primary category in WordPress?

The primary category will be used in the breadcrumbs and even for the Breadcrumbs Schema, provided — you have to set the primary taxonomy to “Categories” under WordPress Dashboard > Rank Math > Titles & Meta > Posts to work correctly.

How do I add a category in Yoast breadcrumbs?

To find the Yoast SEO primary category feature in WordPress, go to the Document tab in the sidebar and then to the Categories tab. Select your categories and use the dropdown menu below them to se the primary category. Done!


1 Answers

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 );
like image 119
Eji Osigwe Avatar answered Sep 18 '22 19:09

Eji Osigwe