Single category: Category1
Two categories: Category1 and Category 2
Three categories: Category1, Category2 and Category3
Four categories: Category 1, Category 2, Category 3 and Category 4
And so forth.
the_category() function has no way of telling how many categories there are, and so can’t do something fancy like inserting the word “and” between the penultimate (second-to-last) and ultimate categories. So I just made a plugin with a new function called
Go ahead and save this text as a file with a “.php” extension, and drop it in your plugin folder. After activating it, you will be able to use a new function in your WordPress template. The function is
the_nice_category(). You will replace the instance of
the_nice_category() in the “posted” section of your main index file.
the_nice_category() takes two optional parameters. The first is the text string to appear between categories when the category on the right isn’t the last category. This defaults to “, ” (a comma and a space). The second parameter is the text string to appear between the penultimate category, and the last category. This defaults to ” and ” (the word “and” buffered by spaces.)
If you wanted to display your categories like the default, but with double quotes around them, you would use this code:
"<?php the_nice_category(', "', '" and "'); ?>"
Notice that you need to place quotes on either side of
the_nice_category(). This is to put the quotes at the beginning of the first category, and at the end of the last category.
Also, if you want to determine if there are multiple categories, you can do so by using
This code will output “Category: ” if there is only one category, and “Categories: ” if there are more than one.
<?php if (count(get_the_category()) > 1) echo 'Categories: '; if (count(get_the_category()) === 1) echo 'Category: '; ?>
- version 1.5.1, updated for WordPress 1.5.1 compatibility.
- version 1.5, updated for WordPress 1.5 compatibility.
- version 1.1, merged in updated WP 1.3 the_category() code (only change is that it won’t throw out an error if there are no categories for that entry). Should work fine with WordPress 1.2 as well.
- version 1.0, the initial release.