Skip to content

Instantly share code, notes, and snippets.

@JiveDig
Last active December 1, 2022 21:24
Show Gist options
  • Select an option

  • Save JiveDig/5d1518f370b1605ae9c753f564b20b7f to your computer and use it in GitHub Desktop.

Select an option

Save JiveDig/5d1518f370b1605ae9c753f564b20b7f to your computer and use it in GitHub Desktop.
Get the primary term of a post, by taxonomy. If Yoast Primary Term is used, return it, otherwise fallback to the first term.
<?php
/**
* Gets the primary term of a post, by taxonomy.
* If Yoast Primary Term is used, return it,
* otherwise fallback to the first term.
*
* @version 1.3.0
*
* @link https://gist.github.com/JiveDig/5d1518f370b1605ae9c753f564b20b7f
* @link https://gist.github.com/jawinn/1b44bf4e62e114dc341cd7d7cd8dce4c
* @author Mike Hemberger @JiveDig.
*
* @param string $taxonomy The taxonomy to get the primary term from.
* @param int $post_id The post ID to check.
*
* @return WP_Term|false The term object or false if no terms.
*/
function jivedig_get_primary_term( $taxonomy = 'category', $post_id = false ) {
// Bail if no taxonomy.
if ( ! $taxonomy ) {
return false;
}
// If no post ID, set it.
if ( ! $post_id ) {
$post_id = get_the_ID();
}
// Bail if no post ID.
if ( ! $post_id ) {
return false;
}
// Setup caching.
static $cache = null;
// Maybe return cached value.
if ( is_array( $cache ) ) {
if ( isset( $cache[ $taxonomy ][ $post_id ] ) ) {
return $cache[ $taxonomy ][ $post_id ];
}
} else {
$cache = [];
}
// If checking for WPSEO.
if ( class_exists( 'WPSEO_Primary_Term' ) ) {
// Get the primary term.
$wpseo_primary_term = new WPSEO_Primary_Term( $taxonomy, $post_id );
$wpseo_primary_term = $wpseo_primary_term->get_primary_term();
// If we have one, return it.
if ( $wpseo_primary_term ) {
$cache[ $taxonomy ][ $post_id ] = get_term( $wpseo_primary_term );
return $cache[ $taxonomy ][ $post_id ];
}
}
// We don't have a primary, so let's get all the terms.
$terms = get_the_terms( $post_id, $taxonomy );
// Bail if no terms.
if ( ! $terms || is_wp_error( $terms ) ) {
$cache[ $taxonomy ][ $post_id ] = false;
return $cache[ $taxonomy ][ $post_id ];
}
// Get the first, and store in cache.
$cache[ $taxonomy ][ $post_id ] = reset( $terms );
// Return the first term.
return $cache[ $taxonomy ][ $post_id ];
}
@madushanl
Copy link
Copy Markdown

Thanks, mate. Very useful

@JiveDig
Copy link
Copy Markdown
Author

JiveDig commented Dec 1, 2022

Just updated to add static caching for times when this function may be used multiple times for the same taxonomy/post_id on the same page.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment