foreach((get_the_category()) as $category) {
echo $category->cat_name . ', ';
}
So I’m echoing it like this because I don’t want the categories to appear as hyperlinks, I just want the cat names.
The problem is I can’t get rid of the last separator so it ends up like : category, category, category,
I tried ‘stripping’ it (php seriously confuses me small design mind)
foreach((get_the_category()) as $category) {
echo $category->cat_name . ', ';
echo rtrim($category, ", ");
}
That didn’t trim it though.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
There are two ways to solve this issue. You need a clean array of category names for both, so let’s start with that:
$cat_names = wp_list_pluck( get_the_category(), 'cat_name');
$cat_names is now an array with just the names:
Array
(
[0] => aciform
[1] => Cat A
[2] => Cat B
[3] => Cat C
[4] => sub
)
Now you can use the simple way:
echo join( ', ', $cat_names );
Result: aciform, Cat A, Cat B, Cat C, sub
But my recommendation is to use the grammatically correct list, use wp_sprintf_l():
echo wp_sprintf_l( '%l', $cat_names );
Result: aciform, Cat A, Cat B, Cat C, and sub
wp_sprintf_l() will use a localized separator for the last two items, so in a German site this would output: aciform, Cat A, Cat B, Cat C und sub.
And you don’t even have to care about the correct translation – the proper separator is part of the regular language files.
Method 2
There’s another way to do this using CSS and a pseudo selector to add the commas. You would just need to wrap each category in an HTML tag eg:
foreach((get_the_category()) as $category) {
echo '<span class="category">' . $category->cat_name . '<span>';
}
And then with CSS:
.category:not(:last-child)::after {
content: ",";
}
EDIT: This solution will only work in browsers that support these pseudo selectors (IE 9 and up)
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0