I have this code. This code is used to display all categories in WordPress.
foreach((get_the_category()) as $category) {
echo $category->cat_name . ', ';
}
But even when there's just 1 category showing, the comma behind it is still there. I want it like this:
- 1 category: [category]
- 2 categories: [category], [category]
- And same goes for 3 categories: [category], [category], [category]
Is this possible? I have tried:
foreach((get_the_category()) as $category) {
$getcount = count(get_the_category());
if($getcount > 1) {
echo $category->cat_name . ', ';
} else {
echo $category->cat_name;
}
}
But that's also not the best solution and when there's more than 1 category, the same issue will accur.
Help is much appreciated.
You could use implode()
$categories = array()
foreach((get_the_category()) as $category) {
$categories[] = $category->cat_name;
}
echo implode( ', ', $categories );
why don't you use the_category(', ');
?
It will also list all post categories
You could use implode
:
$categories = []
foreach((get_the_category()) as $category) {
$categories[] = $category->cat_name;
}
echo implode(', ', $categories);
Or you may use implode
with array_map
:
echo implode(', ', array_map(function($category) {
return $category->cat_name;
}, get_the_category()));
try using this.
$str = '';
foreach((get_the_category()) as $category) {
$str .= "$category->cat_name , ";
}
$str = rtrim($str,', ');
echo $str;
The easiest way is simply to use implode
after building up an array
of Category Names within your foreach
Loop. And it takes just a few lines like so:
<?php
$catNames = array();
foreach( (get_the_category()) as $category) {
$catNames[] = $category->cat_name;
}
echo implode(', ', $catNames);