This is from the codex for another template tag:
Use OUTSIDE The Loop
Normally, this tag must be used inside The Loop because it depends on a WordPress PHP variable ($post) that is assigned a value only when The Loop runs. However, you can manually assign this variable and then use the tag just fine.
I wonder if it works for get_the_category() as well. I can’t see why it shuldn’t. Let me know =)
huh… I’ll be.
single_cat_title(POST_ID) doesn’t do anything, but get_the_category(POST_ID) works just fine…
Interesting. Thanks 🙂
See the Replace With examples here:
http://codex.ww.wp.xz.cn/Template_Tags/the_category_head
To get the categor(y|ies) outside The Loop on a single post page, use something like the following when certain of a single category:
<?php
global $post;
$category = get_the_category($post->ID);
echo $category[0]->name; // first category name
?>
or when the possibility of two or more categories exists:
<?php
global $post;
foreach(get_the_category($post->ID) as $category) {
echo $category->name . ' ';
}
?>
Cool bit of code.
How do I make it show the last category out of two/three?
Basically I’m using parent categories for a lot of posts, but some categories have more than one parent category, and I just want to show the child category without it’s parents…
Kafkaesqui,
Thank you for this code;
<?php
global $post;
foreach(get_the_category($post->ID) as $category) {
echo $category->name . ',';
}
?>
How would you assign “echo $category->name . ‘ ‘;” to another variable so it could be used in another PHP function?
For example:
-If I have two cateogories: Stocks and Funds
-And the echo outputs: Stocks,Funds
-Can I assign this to antoher field like: $myWordpressCategory so $myWordpressCategory=”Stocks,Funds” and I can use this in another PHP function.
I’ve tried: $myWordpressCategory = $category->cat_name . ‘,’; but it only returns the last category.
Thank you,
Steve
How can I write ID of the category instead of name?