Finding the category of a post within the WordPress loop
Tags: categories, wordpress
Date: 31st January, 2010
I’d read somewhere that to get the category of a post you used this within the loop:
$post->post_category
…but for some reason this wasn’t returning anything. After a while looking for a solution, I went for an alternative method using the function:
get_the_category()
It complicates the issue slightly, while adding power, by returning the category of a post as an array. Then, each category has it’s own array of credentials, such as id, name and so on. As I knew there was only going to be one category attached to my posts, and I was only texting for a category anyway, for this project I ended up with this:
$cat = get_the_category();
if ($cat[0]->name) {