Last active
September 10, 2020 23:58
-
-
Save mae829/d566d5e285ceac1b9ffce67e33f8bd47 to your computer and use it in GitHub Desktop.
WordPress helper function to retrieve an attribute (or the whole category object) of the primary category. Should be used inside the lop.
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 | |
/** | |
* Get Primary Category | |
* | |
* Get the primary category of the post. | |
* Should be used inside the loop. | |
* | |
* @param string $att Attribute of the category that is desired (if 'all' is passed, will return whole object) | |
* @param boolean $wpseo Whether or not to use WPSEO (if it's on/installed) | |
* | |
* @return string/object Either the first category or primary if WPSEO is on/installed | |
*/ | |
public static function get_primary_cat( $att = 'slug', $wpseo = true ) { | |
if ( class_exists('WPSEO_Primary_Term') && $wpseo !== false ) { | |
$wpseo_primary_term = new WPSEO_Primary_Term( 'category', get_the_id() ); | |
$wpseo_primary_term = $wpseo_primary_term->get_primary_term(); | |
$cat = get_category( $wpseo_primary_term ); | |
// WPSEO will return WP error if there is no set primary category | |
if ( is_wp_error($cat) ) { | |
$post_cats = get_the_category(); | |
$cat = !empty( $post_cats[0] ) ? $post_cats[0] : ''; | |
$cat_display = !empty( $cat->$att ) ? $cat->$att : ''; | |
} else { | |
$cat_display = $cat->$att; | |
} | |
} else { | |
$post_cats = get_the_category(); | |
$cat = !empty( $post_cats[0] ) ? $post_cats[0] : ''; | |
$cat_display = !empty( $cat->$att ) ? $cat->$att : ''; | |
} | |
return $att != 'all' ? $cat_display : $cat; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment