Last active
October 7, 2023 18:16
-
-
Save tarecord/4c7171b9955aee41d91db133af3e1d8f to your computer and use it in GitHub Desktop.
Returns the primary term for the chosen taxonomy set by Yoast SEO or the first term selected.
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 | |
/** | |
* Returns the primary term for the chosen taxonomy set by Yoast SEO | |
* or the first term selected. | |
* | |
* @link https://www.tannerrecord.com/how-to-get-yoasts-primary-category/ | |
* @param integer $post The post id. | |
* @param string $taxonomy The taxonomy to query. Defaults to category. | |
* @return array The term with keys of 'title', 'slug', and 'url'. | |
*/ | |
function get_primary_taxonomy_term( $post = 0, $taxonomy = 'category' ) { | |
if ( ! $post ) { | |
$post = get_the_ID(); | |
} | |
$terms = get_the_terms( $post, $taxonomy ); | |
$primary_term = array(); | |
if ( $terms ) { | |
$term_display = ''; | |
$term_slug = ''; | |
$term_link = ''; | |
if ( class_exists( 'WPSEO_Primary_Term' ) ) { | |
$wpseo_primary_term = new WPSEO_Primary_Term( $taxonomy, $post ); | |
$wpseo_primary_term = $wpseo_primary_term->get_primary_term(); | |
$term = get_term( $wpseo_primary_term ); | |
if ( is_wp_error( $term ) ) { | |
$term_display = $terms[0]->name; | |
$term_slug = $terms[0]->slug; | |
$term_link = get_term_link( $terms[0]->term_id ); | |
} else { | |
$term_display = $term->name; | |
$term_slug = $term->slug; | |
$term_link = get_term_link( $term->term_id ); | |
} | |
} else { | |
$term_display = $terms[0]->name; | |
$term_slug = $terms[0]->slug; | |
$term_link = get_term_link( $terms[0]->term_id ); | |
} | |
$primary_term['url'] = $term_link; | |
$primary_term['slug'] = $term_slug; | |
$primary_term['title'] = $term_display; | |
} | |
return $primary_term; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample Usage
Display the primary category from the default WordPress category taxonomy
Display the primary term from a custom taxonomy
Add a link to the primary category's archive page