get primary category of post wordpress code example

Example: get primary category of post wordpress

This is not a native wordpress feature, but a feature of Yoast SEO (see here).

You can check for primary status the following way:

<?php
$term_list = wp_get_post_terms($post->ID, 'category', ['fields' => 'all']);
foreach($term_list as $term) {
   if( get_post_meta($post->ID, '_yoast_wpseo_primary_category',true) == $term->term_id ) {
     // this is a primary category
   }
}
?>
If you are using custom taxonomies, use the meta_key

_yoast_wpseo_primary_CUSTOM_TAXONOMY
instead

Tags:

Misc Example