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.
try using this.
You could use
implode
:Or you may use
implode
witharray_map
:You could use implode()
why don't you use
the_category(', ');
? It will also list all post categoriesThe easiest way is simply to use
implode
after building up anarray
of Category Names within yourforeach
Loop. And it takes just a few lines like so: