-
-
Save sultann/e29c41a35dbfd1ba854cc48360667d2d 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.
This file contains hidden or 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 the primary term of a post, by taxonomy. | |
| * If Yoast Primary Term is used, return it, | |
| * otherwise fallback to the first term. | |
| * | |
| * @version 1.1.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|bool 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(); | |
| } | |
| // 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 ) { | |
| return get_term( $wpseo_primary_term ); | |
| } | |
| } | |
| // 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 ) ) { | |
| return false; | |
| } | |
| // Return the first term. | |
| return $terms[0]; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment