Find Post’s Primary Category with Yoast

Categories:

When using the Yoast SEO plugin, you can define a Primary Category for each post.
Here is the code to find it:

// Check class so code does not cause errors if you remove Yoast SEO
if ( class_exists('WPSEO_Primary_Term' ) { 
	$yoast_primary_term = new WPSEO_Primary_Term( 'category', get_the_id() );
	$yoast_primary_term_id = $yoast_primary_term->get_primary_term();
	$primary_category = get_term( $yoast_primary_term_id );
	if ( !empty( $primary_category->name) ) {
		// Print the Primary Category. Extend as required...
		echo $primary_category->name; 
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *