Last active
September 11, 2020 08:13
-
-
Save chaance/8d3ca0ca787ea8cf2851fb1cfac36805 to your computer and use it in GitHub Desktop.
Get the Yoast SEO primary term for a given taxonomy.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment