how do I get the cat ID inside the Template. Very important:
I can not do it by the name, because we have muliple cats with the same name. Only the slug is different. If I’d get the slug, it would be okay, too.
But like I said: I can not use the Cat title…..
Leave a Reply
You must be logged in to post a comment.
$wp_query->get_queried_object()
will give you the “currently queried object”. On a category archive this is the category object, on a author page this is the author, on a single post this is the post itself, … well, you get the the idea. If you only want the ID you can also use$wp_query->get_queried_object_id()
.base on my search you must use this:
Umm, I can’t comment yet, but VicePrez’s answer does work. The following works just fine on a category archive page (although you probably want to do something other than just echo it):
EDIT: Scratch that, it worked for me until I came across a category that didn’t have a post, then it picked up the subcategory instead of the main category. You can’t rely on get_the_category on a category template page.
Unless I am misunderstanding the question, I think you can also add the category id/slug to the body class:
@Jan Fabry’s response is actually the correct answer, here’s why: Since WordPress allows multiple categories for a post, using
$category = get_the_category()
and querying$category[0]
will not work in every case since what you’re actually doing is asking for the first category of the first post. Imagine you have categories A, B and C. If you have only one post, it has categories A and B and you’re inside B’s category page, you may end up with A’s information instead.That’s why it’s better to use
$category = $wp_query->get_queried_object()
, because in the previous example it will always get you B’s information when you’re inside B’s category page.You could use
get_the_category()
to do that.Example:
You could use:
to view the array of objects that are returned.
Most of the above examples work but if you are using multiple categories NONE (as of writing, WP version 3.6) of the other methods work to get all the categories that have been passed to either “cat” or “category_name”.
The only way I have found is to pull the data from:
For some reason this returns a different value to
get_query_var( 'category_name' )
which only returns the first category.When using multiple categories you will have to use some function like
explode
to get an array of category slugs, then loop through that to grab all the IDs:Obviously there needs to be some considerations when using AND (+) or OR (,) operators.
You can also use get_the_terms inside your archive template or functions file and use the 2nd parameter to specify your taxonomy as a category.