I could not get the accepted answer to work.
I modified this to fit my needs
$cat_name = ''; // I have this set in some shortcodes
if (!isset($cat_name) || $cat_name == '') {
if ( class_exists('WPSEO_Primary_Term') ) {
// Show the post's 'Primary' category, if this Yoast feature is available, & one is set. category can be replaced with custom terms
$wpseo_primary_term = new WPSEO_Primary_Term( 'category', get_the_id() );
$wpseo_primary_term = $wpseo_primary_term->get_primary_term();
$term = get_term( $wpseo_primary_term );
if (is_wp_error($term)) {
$categories = get_the_terms(get_the_ID(), 'category');
$cat_name = $categories[0]->name;
} else {
$cat_name = $term->name;
}
} else {
$categories = get_the_terms(get_the_ID(), 'category');
$cat_name = $categories[0]->name;
}
}
echo $cat_name;
I have edited a working example to be more self contained, I used it for custom taxonomy so used get_the_terms() instead of get_the_category(). This code has not been tested in its current state.
You can then use get_term() to get the WP_Term object:
// Will return `false` if no primary term has been set
$primary_term_id = yoast_get_primary_term_id( 'taxonomy_slug', $post_id_or_object );
if ( $primary_term_id ) {
/** @var WP_Term $primary_term */
$primary_term = get_term( $primary_term_id );
}
For those scenarios where you just need the term’s name, you can use yoast_get_primary_term():
// Will return an empty string if no primary term has been set
$primary_term_name = yoast_get_primary_term( 'taxonomy_slug', $post_id_or_object );
3
Answers
Hi you can get using postmeta table.
I could not get the accepted answer to work.
I modified this to fit my needs
I have edited a working example to be more self contained, I used it for custom taxonomy so used get_the_terms() instead of get_the_category(). This code has not been tested in its current state.
The Yoast SEO plugin now has a dedicated function —
yoast_get_primary_term_id()
— for getting the primary term’s ID:You can then use
get_term()
to get theWP_Term
object:For those scenarios where you just need the term’s name, you can use
yoast_get_primary_term()
: