Skip to content

Instantly share code, notes, and snippets.

@kjbrum
Last active February 8, 2017 03:48
Show Gist options
  • Save kjbrum/3370b6d05ae0c7f0c31e to your computer and use it in GitHub Desktop.
Save kjbrum/3370b6d05ae0c7f0c31e to your computer and use it in GitHub Desktop.
Get the first category of a post.
<?php
/**
* Get the first category of a post.
*
* @param int $id The id of a post
* @param int $id The field value to return
* @return mixed The category object or single field
*/
function wp_get_first_category( $id=null, $field='all' ) {
// Check if only a field value was supplied
if ( $id ) {
if ( ! is_numeric( $id ) ) {
global $post;
$field = $id;
$id = $post->ID;
}
} else {
global $post;
$id = $post->ID;
}
// Get all the post's categories
$categories = get_the_category( $id );
// Check if there are any categories, if so get the first
if ( empty( $categories ) ) {
return false;
} else if ( isset( $categories[0] ) ) {
$cat = array_shift( $categories );
} else {
$cat = $categories;
}
// Check if we should be returning a single field, or the whole object
if ( $field == 'all' ) {
return $cat;
} else {
return $cat->$field;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment