Skip to content

Instantly share code, notes, and snippets.

@chaance
Last active September 11, 2020 08:13
Show Gist options
  • Save chaance/8d3ca0ca787ea8cf2851fb1cfac36805 to your computer and use it in GitHub Desktop.
Save chaance/8d3ca0ca787ea8cf2851fb1cfac36805 to your computer and use it in GitHub Desktop.
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;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment