Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Wordpress Category from Single Post

I'm finishing up a WP theme, and I'm on the single.php template. I'm having some issues because I need to access the parent category that a post is in in order to display certain images and XML content.

Here is an example of what I'm talking about. The following is the end url of a single post:

/andrew/leaf-art-2/

/andrew/ is the category, and leaf-art-2 is the single post. When I am on the single post, I am having trouble getting single_cat_title(); to return the category that the current post is in. I am using single_cat_title(); instead of the_category(); because it displays the string value of the category which I then use to place a picture of the artist (whose category this is) on their posts. I don't have any use for the url, I just need the string with the category name.

Any good ways of doing this? I have been searching the Wordpress Codex and lots of forums, and haven't found any answers yet.


The following was my original post.

I have set up a category called "artists" which when I run single_cat_title("", false); I can get the string value of the category and then use it to search for the appropriate artist image using XML.

This works fine on the category.php template page.

The problem is that when I'm actually inside of a single post that has the "artists" category, single_cat_title(); doesn't output any information to the page, thereby keeping me from accessing the XML data.

I need to, while in the "artists" > "sample" post, be able to get from WP the category.

P.S. the above category is one of many that is using this setup, which is why I can't hardcode it.

like image 565
Ian Avatar asked Nov 27 '10 02:11

Ian


People also ask

How do I get all the categories of a custom post type in WordPress?

use get_terms() function to fetch custom taxonomy by its slug, in your case slug is dining-category. read function refrence from wordpress codex website and try this.

How do I find the category ID of a WordPress post?

All categories and tags are actually terms inside a WordPress taxonomy. The same editor handles them. Now you can find your WordPress tag ID also in a similar way. Visit Posts » Tags and then hover the mouse over the tag whose ID you want to view.


2 Answers

How about get_the_category?

You can then do

$category = get_the_category(); $firstCategory = $category[0]->cat_name; 
like image 81
Chris Avatar answered Sep 23 '22 22:09

Chris


For the lazy and the learning, to put it into your theme, Rfvgyhn's full code

<?php $category = get_the_category(); $firstCategory = $category[0]->cat_name; echo $firstCategory;?> 
like image 23
Sjoerd Avatar answered Sep 22 '22 22:09

Sjoerd