开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜