Created
April 30, 2020 13:13
-
-
Save hasinhayder/4f306bdcb1f0e009dc7604a6f160baae to your computer and use it in GitHub Desktop.
Get single category for a post in different way
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
//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); | |
} |
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
// 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; | |
} |
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
// 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