Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WordPress helper function to retrieve an attribute (or the whole category object) of the primary category. Should be used inside the lop.
<?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
You can’t perform that action at this time.