pusatdata icon

How Show Slug Category

pusatdata | PRO | 07/13/17 01:49:25 AM UTC | 0 ⭐ | 418 👁️ | Never ⏰ | []
text |

1.24 KB

|

None

|

0 👍

/

0 👎

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
<?php
$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;
?>
 SIMPEL:
<?php $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 $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.
?>
 atau
<?php echo get_cat_slug(); ?>

Comments