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
1
2
3
4
5
6
7
<?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

PHP
1
2
3
4
5
6
7
8
$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.
PHP
1
2
3
4
5
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
1
2
3
4
<?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?

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

0 comments:

Post a Comment

 
Top