Shoora
4/22/2019 - 10:10 AM

Get the Yoast SEO primary term for a given taxonomy.

Get the Yoast SEO primary term for a given taxonomy.

<?php
/**
 * Get primary taxonomy term (YoastSEO).
 *
 * @param mixed   $taxonomy     Taxonomy to check for.
 * @param boolean $term_as_obj  Whether to return an object or the term name.
 * @param int     $post_id      Post ID.
 * @return mixed                The primary term.
 */
function xx_get_primary_tax_term( $taxonomy = 'category', $term_as_obj = true, $post_id = 0 ) {
	if ( 0 === $post_id ) {
		$post_id = get_the_ID();
	}
	$terms = get_the_terms( $post_id, $taxonomy );

	// Check if post has a tax term assigned.
	if ( $terms ) {
		if ( class_exists( 'WPSEO_Primary_Term' ) ) {

			// Show the post's 'Primary' term.
			// Check that the feature is available and that a primary term is set.
			$wpseo_primary_term = new WPSEO_Primary_Term( $taxonomy, $post_id );
			$wpseo_primary_term = $wpseo_primary_term->get_primary_term();
			
			// Set the term object.
			$term_obj = get_term( $wpseo_primary_term );
			if ( is_wp_error( $term_obj ) ) {
				$term_obj  = $terms[0];
			}
		} else {
			$term_obj = $terms[0];
		}

		if ( ! empty( $term_obj ) ) {
			return $term_as_obj ? $term_obj : $term_obj->name;
		}
	}
}