Last active
August 21, 2019 23:20
-
-
Save BicanMarianValeriu/77b57b740e3adc1cc330c61b9484e95c to your computer and use it in GitHub Desktop.
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
/** | |
* 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 get_primary_tax_term( $post_id = 0, $taxonomy = 'category', $term_as_obj = true ) { | |
if ( 0 === $post_id ) { | |
$post_id = get_the_ID(); | |
} | |
$terms = get_the_terms( $post_id, $taxonomy ); | |
if ( $terms ) { | |
if ( class_exists( 'WPSEO_Primary_Term' ) ) { | |
$wpseo_primary_term = new \WPSEO_Primary_Term( $taxonomy, $post_id ); | |
$wpseo_primary_term = $wpseo_primary_term->get_primary_term(); | |
$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 (bool) $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