How to get the current category from the URL in Wordpress

There are a variety of ways to get the current category in WordPress, this method is my pick as it works anywhere and doesn’t need to be used in the loop.

This method only works if the site you are working on has been setup to use category slugs in the URL. It extracts the category slug from the query_vars, picks out the last slug (in case the user is on a child category) and then looks up the category by it’s slug.

Here’s the snippet:

$slugs = explode('/', get_query_var('category_name'));
$currentCategory = get_category_by_slug('/'.end($slugs));

As previously mentioned this bit of code can be used anywhere to figure out the current category.