Yoast WP Primary Category - Make Primary

The 3.1 update to Yoast’s WordPress SEO plugin brought with it a new feature—the ability to set a “Primary” category for a post. You’ll now see a “Make Primary” link when selecting categories (or a bold “Primary” label if one has been set). Some people may confuse this for a native WordPress feature. Which, arguably it should be!

The WordPress SEO plugin uses this when generating its optional breadcrumb links. So the most important category can appear, rather than one of many categories that may be applied to a post.

But what about using this in a custom WordPress theme? We can do that.

Display the Primary Category, if it’s Available

On the site I used this for, I wanted to display a single category along with the post, on the post archive pages. The design was such that showing multiple categories was unwanted and would take up too much space. Using the_category() function will show all categories assigned to a post.

The following code will display Yoast’s primary category if it’s available, otherwise it will fallback to displaying the first category returned by get_the_category() (I think that this is the first category that has been assigned).

Note that this code isn’t officially provided by Yoast. I figured it out by digging around on the plugin’s GitHub repository. So it is possible that their API / functions could change in future versions and cause something to break. So just be aware of this before integrating into your custom WordPress theme:

I’ve also added an option $useCatLink which you can set to false if you do not want the categories to be linked.

Comments on this Article

  1. Olivier says:

    Hi, thank you for this piece of code. I have used it successfully on my theme to retrieve the Primary category.

  2. Jimmy says:

    Thank you for the writeup. Unfortunately this didn’t work for me – the constructor would only return an empty object.

    I was able to get around it by looking up the post_meta in the database (called _yoast_wpseo_primary_category) and using get_term() to get it there.

  3. Karen says:

    Have you figured out a way to get next-previous post links based on primary category?

  4. Conrad says:

    hello i wanna display primary cat. and other 2 cat. too. how can i set display limit?

  5. Julie says:

    Brilliant! I was able to use it without modification. Thank you so much!

  6. Karen says:

    Very helpful – thank you!

Leave a Reply

You can use the <pre> tag to post a block of code, or <code> to highlight code within text.