Get Category Slug of Current Category in WordPress

How to Get Category Slug of Current Category in WordPress

in Categories
Google+ LinkedIn

When developing a WordPress theme or a plugin, you may have come across times when you may wish to get category slug in certain pages. May be you are modifying the WordPress category archives or you may have some other reason for wanting to retrieve category slug, in this article we will show you a simple way to get category slug of current category and some other common category variables like name, ID and description.

There are a variety of ways to return the variables of current category in WordPress, this method is my pick as it works anywhere and doesn’t need to be used in the loop. First we will get the category ID and then with the help of category ID, we will easily get category slug and other variables.

You can use this code snippet in your theme files anywhere you wish. If your post have multiple categories associated with it, then this snippet will return category variables for first category only.

    // get category slug in wordpress
    if ( is_single() ) {
        $cats =  get_the_category();
        $cat = $cats[0];
    } else {
        $cat = get_category( get_query_var( 'cat' ) );
    $cat_slug = $cat->slug;
    echo $cat_slug;

Above WordPress snippet will print category slug only but you can also add couple of more category variables that you can use in your project.

    // other category variables
    $cat_id = $cat->cat_ID;
    $cat_name = $cat->name;
    $cat_description = $cat->description;

Share the love

If you like this snippet, share it with others!

3 Replies on "Get Category Slug of Current Category in WordPress"

  1. rhf

    Thank you so much

  2. Sundar

    Nice tutorial! This massively helpful to me. I absolutely like this tutorial. It just made my work easier. I want to encourage you to continue your great job.


  3. ????? ??? ?? ?????

    you’re article is nice

Leave a Reply

Your email address will not be published. Required fields are marked *