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.