strip last comma from get_the_category

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.

Leave a Comment