How to Get Category Slug in WordPress

Advertisement

Using category slug is the best way to use in wordpress custom query code as the category name does not always work. Rather use ‘category-slug’ instead, in this tutorial I’ll show you how to get WordPress slug in Category or in single page view.

For category view you can use this code snippet.


<?php
if(is_category()) {
	$category = get_query_var('cat');
	$current_cat = get_category($cat);
	echo 'The slug is ' . $current_cat->slug;
}
?>

For single view or post view


$terms = get_the_terms( $post->ID , 'category');
if($terms) {
	foreach( $terms as $term ) {
		$cat_obj = get_term($term->term_id, 'category');
		$cat_slug = $cat_obj->slug;
	}
}
echo 'The slug is '. $cat_slug;

Still hungry?

If in the case you only want to get category slug using category ID don’t worry folks, I’ve provided a solution on it too.

Step 1:

In your function.php file, put this function.


function get_cat_slug($cat_id) {
	$cat_id = (int)$cat_id;
	$category = &get_category($cat_id);
	return $category->slug;
}

Step 2:

Once done, you can use the function like the below code.


<?php
echo get_cat_slug(1);
// Where 1 is the category ID, this code will display the slug of the category ID 1.
?>

Don’t know how to get WordPress Category ID?

Visit this link Get Single Taxonomy ID to learn more.

That’s it happy blogging, you can share your idea below.

Advertisement