0
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.

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.

  • Yeah, that's fantastic toscho, thanks! I prefer the second one, though it's not quite grammatically correct if it lists more than 3 categories. Since it says category, category, and category the last comma in that sentence shouldn't really be there. – andy Feb 26 '13 at 0:52
  • @andy That’s a Serial comma and quite correct. You can filter 'between_last_two' and change it if you want. – fuxia Feb 26 '13 at 0:56
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)

  • 2
    This would however fail on browsers that does not support the pseudo classes – Pieter Goosen Oct 12 '15 at 7:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.