x
 
Create New Page
 View Previous Changes    ( Last updated by Ingmar Greil )

Grammatically correct list of categories

Question

Some user wanted a “grammatically correct” list of categories; not merely displaying all categories of a particular entry, but separating them with a comma and prepending the last one with “and”:

Example: Filed under: Foo, Bar and Splat.

Answer

The solution is to use PHP to write the categories to an array, then loop through it and add “and” at the last but one position:

<?php 

// pull the categories into an array, and separate by comma 
$categories explode(",","{categories backspace="1"}{category_name},{/categories}"); 

// loop through & output all the elements of the array 
for ($i 0$i count($categories); $i++) print $categories[$i]

if (
count($categories) > 1// make sure no "and" gets added if there's only a single category 
if ($i == count($categories)-2print ' and '// if the last-but-one element comes up, add "and" 

// otherwise just add a comma and a space, except after the final element 
elseif ($i != count($categories)-1print ", "

// close the "$categories > 1" clause 
// close "for" loop 

?> 

More information: See this thread on the forums for reference

Category:Categories Category:Entries

Category:EE1

Categories: