Very new to WordPress and web design. I have this function for separating categories with a comma ",". But it also adds the comma after the last category. Making it look like this:
Category1, Category2, Category3,
When I want it like this:
Category1, Category2, Category3
Without the last comma behind Category3
How can I stop the function from adding the last comma?
<?php
$category_detail = get_the_category($post->ID); //$post->ID
foreach ($category_detail as $cd) {
echo $cd->cat_name . ', ';
}
?>
Regards
3
Answers
There is many approaches to splitting arrays values.
Indeed you could achieve it via a
foreach
loop, by counting iterations.Tho a more concise approach would be using the
implode()
native function:With this foreach loop you are actually converting an array into string. Thus, if it is more understandable to use, you could just erase the last char like this:
I was being lazy, and searching Google for this, but none of these were quite what I was searching for. I wrote this and will leave it here for anyone else on a similar search.
Add this to your functions.php:
Then in your templates, echo the function and pass in the post_id and a *class (optional)