Retriving category name of a post
How to retrieve the Category name out 开发者_开发百科of a post ID.
Is the following the optimum way, or is there any simpler method.....
$category = get_the_category($post_id);
$cat_name = $category->cat_name;
I'm not entirely sure what you're asking but if you are looking for shorter syntax:
$cat_name= get_the_category($post_id)->cat_name;
If you're just trying to print a list of categories belonging to a post, use...
the_category( $separator = '', $parents='', $post_id = false )
which echoes out links, or
get_the_category_list( $separator = '', $parents='', $post_id = false )
which returns a string with links.
If you want the post categories as an array of objects use get_the_category( $id = false )
.
The post ID is optional: if it's omitted the functions assume that you are talking about global $post
. If you're in the loop this will work, otherwise you'll have to pass the post ID.
In any case, a post can belong to several categories, not just one, even though the function names imply otherwise.
All these functions reside in wp-includes/category-template.php
.
精彩评论