Skip to content

Instantly share code, notes, and snippets.

@hasinhayder
Created April 30, 2020 13:13
Show Gist options
  • Save hasinhayder/4f306bdcb1f0e009dc7604a6f160baae to your computer and use it in GitHub Desktop.
Save hasinhayder/4f306bdcb1f0e009dc7604a6f160baae to your computer and use it in GitHub Desktop.
Get single category for a post in different way
//Get a single category name with id, name pair
function get_single_category( $post_id = null ) {
global $post;
$post_id = is_null( $post_id ) ? $post->ID : $post_id;
$categories = wp_get_post_categories( $post_id, array( 'fields' => 'all' ) );
shuffle( $categories );
$single_category = array_shift( $categories );
return array($single_category->term_id => $single_category->name);
}
// Get a random choice
function get_single_category( $post_id = null ) {
global $post;
$post_id = is_null( $post_id ) ? $post->ID : $post_id;
$categories = wp_get_post_categories( $post_id, array( 'fields' => 'names' ) );
shuffle( $categories );
$single_category = array_shift( $categories );
return $single_category;
}
// Get a name, whichever comes first
function get_single_category( $post_id = null ) {
global $post;
$post_id = is_null( $post_id ) ? $post->ID : $post_id;
$categories = wp_get_post_categories( $post_id, array( 'fields' => 'names' ) );
$single_category = array_shift( $categories );
return $single_category;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment