问题
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.
回答1:
How about get_the_category?
You can then do
$category = get_the_category();
$firstCategory = $category[0]->cat_name;
回答2:
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;?>
回答3:
<div class="post_category">
<?php $category = get_the_category();
$allcategory = get_the_category();
foreach ($allcategory as $category) {
?>
<a class="btn"><?php echo $category->cat_name;; ?></a>
<?php
}
?>
</div>
来源:https://stackoverflow.com/questions/4289879/get-wordpress-category-from-single-post