Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.
                                            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.

share|improve this question

1 Answer 1

up vote 1 down vote accepted

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.

share|improve this answer
    
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. –  toscho Feb 26 '13 at 0:56

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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