How to get the category name for a post
I love proper markup, and so I like the link title attribute to display helpful info – not just a dumb repetition of the post’s title. Here’s how to display something a bit more informative, like the category the post is in.
It took me a while to figure out how to retrieve the category name from the post, because I was looking in the wrong place – was expecting it to be an element of $post, like $post->ID or $post->category. But $post->cat_name was missing somehow, haha. Of course, it’s quite simple to get the post’s category name, by using the get_cat_name function:
$p_cat = get_the_category($post->ID); $p_catId = $p_cat[0]->cat_ID; $p_catName = get_cat_name(p_catId); $result = "<a href='".get_permalink($post->ID)."' title='".p_catName.': '. $post->post_title ."'>";
The link title will display something like “snippets: how to get the category name”.
1 comment
Thanks for help man.
I face with the same problem.
In snippets:
Featured projects:
Most popular:
RSS Links