Get primary category if more than one is selected?
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.
If you are using "The SEO Framework" plugin instead of "Yoast SEO":
$taxonomy = 'category';
$post_id = get_the_ID();
$terms = wp_get_post_terms($post_id, $taxonomy, ['fields' => 'all']);
$primary_term = intval(get_post_meta( $post_id, '_primary_term_' . $taxonomy, true ));
foreach($terms as $term) {
if( $primary_term == $term->term_id ) {
// this is a primary category
}
}
References:
https://github.com/sybrew/the-seo-framework/blob/4262ea703eaaa50813d8cd4ac13f4537b5c6a4cc/inc/classes/post-data.class.php#L633