A fresh mix of code snippets and tutorials

WordPress: Get category slug on archive views

When working with WordPress, you can get the current post category using the function get_the_category(). That’s great but it works only on single posts and pages. This post explains how to get the category for archive views like date archives, category archives, search results, and so forth.

The key: get_queried_object()

The key function to help us achieve this is get_queried_object(). Here is how we can use it to get the category slug (or any other property) on any archive view:

$obj = get_queried_object();
$cat_slug = $obj->slug;

This outputs the first post category when called on any archive view.

Fun example

To illustrate how the above technique works, here is a more specific example that can be added to any theme (or child theme) functions.php:

function shapeSpace_test_current_category($content) {
	$string = '';
	if (is_category()) {
		$obj = get_queried_object();
		$string = '<!-- '. $obj->slug .' -->';
	return $content . $string;
add_filter('the_excerpt', 'shapeSpace_test_current_category');

Of course, this is very basic, not meant for production use. If you want to implement something similar on a live site, you would want to do some proper checks, like using isset() or similar to check if the slug property exists. Basically this code snippet is just an example to show you how it works in general.

When added to your theme, the above code will output the category slug as an HTML comment. It will look something like this in the source code of any category archive page:

<!-- movies -->

An inline comment such as the above is added to each post excerpt via the_excerpt hook, so there will be a category slug displayed in the source code for each post in the archive.

Learn more

WordPress Themes In Depth