Get Category Slug of Current Category in WordPress


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;

Leave a Reply

Random Post Selection ::

Recent Posts

Unlock Unlimited Downloads