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”.

0

in snippets

post a commentsave the linkrate as favorite

leave a comment

Your e-mail address will not be made public or shared with others. Required fields are marked with a *

*
*

Optionally, you could use these HTML tags: <b> <cite> <code> <i> <strike> <strong>

Please leave these two fields as-is: