It shouldn’t be this hard!! Here is a quick function for getting the Category ID for a WordPress Category Page. Once you get the Category ID, a world of possbilities opens up. You can get the category object and all the info you need related to that Cat. I can’t believe how hard it was to find this on Google. Ultimately, I had to piece together a couple of different posts to get to this since they weren’t quite right.
If you’ve got a better way of getting this…please share! Here’s what I came up with:
function getCurrentCatID(){ global $wp_query; if(is_category() || is_single()){ $cat_ID = get_query_var('cat'); } return $cat_ID; } //To get the full category object, try this: $cat = get_category(get_query_var('cat'),false);
Uggg…that shouldn’t have been so hard to find. Big ‘G’, you treated me bad!
[Follow-up] – as Steve notes below, try get_the_category() and see if that does what you need before implementing the function above. Thanks, Steve!
Cheers,
Byron
Thanks for the sharing. Will try out the code on my new site. Need to exclude certain category from showing. I think the function you wrote to get the Cat ID will help.
Hi,
I searched a lot for a useful function like this, but as I cannot use yours (your function does not return the current cat ID when I have child cats in the current parent cat), I show you mine (don’t know if it’s better or not indeed but it works 🙂 ).
term_id;
}
?>
Have a great day 😉
Thanks a lot, it works like a charm!
Logically the category id should be stored in a variable somewhere when you’re viewing a category page…
I’ve spent way too long looking for this as well. As it turns out, $cat contains the category ID on my site’s category pages, but maybe my theme is setting it.
Hi Becca,
$cat worked for me as well. I did a quick Google, but didn’t see a reference to it, so it may or may not be a solid method…but as long as it work!!!
Thanks for the tip!
Byron
I think what you need is: get_the_category(). It returns the current category on a category page.
Thanks a lot, it works like a charm!
Logically the category id should be stored in a variable somewhere when you’re viewing a category page…
This was SUPER helpful. Thanks so much for sharing! I definitely owe you one. If you’d like a free premium theme, let me know 😉
This works really well. I am using it to determine which level my subcategories are on.
Thank you for your insight … and google searchability.
thanks a lot!!!!!! i’m getting mad while looking for answers in google 😎
get current category wordpress
get_the_category() is used for listing all of the categories, whereas this function is particularity useful when you get into advanced post setups that revolve around conditional post/category styling.
Simple yet effective 🙂
Thanks a lot!
Worked for me! When posts are tagged in multiple categories, this is handy for retrieving the actual category page your on. Thanks 🙂