I have a taxonomy called "location". I'm outputting a comma separated list of these taxonomy terms for a post. This is fine, but I don't know how to split the second-to-last and last items with "and" instead of a comma.

Here is my code. Is there a way to do it using the counter maybe?

$locations = get_the_terms($post->ID, 'location');

$locations = array_values($locations);
for($cat_count=0; $cat_count<count($locations); $cat_count++) {

  echo $locations[$cat_count]->name;

  if ($cat_count<count($locations)-1){
    echo ', ';


Note: This code is in the sidebar for a category archive template and inside a WP_Query, so it's all within the loop. The WP_Query is outputting multiple posts of a custom post type called Projects and I'm trying to list the location tax terms for each one.


This is how your code should look like I added some comments so you will understand its simple programming not really wordpress related.

$locations = get_the_terms($post->ID, 'location');
$locations = array_values($locations);

$total_locations = count($locations); // the total start from 1

for($i = 0; $i < $total_locations; $i++) {

    echo $locations[$i]; // echo the location

    if($i < $total_locations-2) { // so for comma you need to check if the for loop variable is - 2 because the loop start from 0
        echo ', '; // echo comma
    } elseif($i < $total_locations-1) { // and here is just -1 because you want to print it before the last one because this we use the less than sign in both of our conditions 
        echo ' and '; // echo and
  • Thank you this worked for me. I just had to change this: echo $locations[$i]; to echo $locations[$i]->name; – Xav Jan 17 '17 at 0:07

You should replace fragment in your code which echoes comma by the following:

if ($cat_count<count($locations)-2) {
  echo ', ';
if ($cat_count=count($locations)-2) {
  echo 'and ';

This will output comma after all elements of array, except last and previous to last elements.

Elements in array have indexes from 0 to "count ($locations)-1".

Element previous to last has index count($locations)-2. After this element, code outputs " and ".

  • Thank you for your post, but please explain how this solves the problem. Code only solutions are discouraged. – Dave Romsey Jan 16 '17 at 22:09
  • Thanks for your answer. However the page keeps timing out when I use this. Something else must be wrong in my code. I'll update my question. – Xav Jan 16 '17 at 23:55

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