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.
February 2022 Update:
I just updated the script with a new an improved version, since this has been pretty popular and it needed a few adjustments. The primary meta key is now retrieved via the post meta value, which is a little more futureproof. It’s now a function with a parameter for showing the link or not. And both the URL and category name are now escaped with the WP functions _esc_url_ and _esc_html_e_ (displays symbols like “&” properly as discussed in some of the comments).
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: It is possible that Yoast may change the way that it stores the primary category in the future. For now we are relying on this being stored in the post meta “_yoast_wpseo_primary_category”.
I’ve also added an option $useCatLink which you can set to false if you do not want the categories to be linked.