Get Category Slug of The Post in WordPress

wordpress code

I wanted to get the category slug for the current post but calls like single_cat_title() were not usable:

  • Return null unless you are on a category page
  • Can’t get to the slug string

If each of your post has only 1 category, this is the solution:

global $post;
$categories = get_the_category($post->ID);
$post_cat_slug = $categories[0]->slug;

Explanation by line:
/* get current post info */
/* get the category list for this post */
/* get slug for the 1st category */

To get a cleaner code, I put it in my functions.php and called from my template file.