I am trying to display a list of event producers, which are stored as a taxonomy. For each event (custom post type) there can be anywhere between 1 and many producers, so I would like to list them, comma separated, with a "&" between the second to last one and last one. The below function does the job, except in the case of only having one producer. How would I make this work for 1 producer or many producers at the same time?
function the_producers($post_id = false) {
if ($post_id == false) {
$post_id = get_the_ID();
}
$producers = get_the_terms($post_id, 'producers');
$prods = array();
foreach ($producers as $producer) {
$prods[] = $producer->name;
}
$str = array_pop($prods);
if ($prods) {
$str = implode(', ', $prods).' & '.$str;
return $str;
} else {
return false;
}
}
I've tried counting the number of iterations and if there's only 1, just returning the single producer, but that doesn't seem to display anything for some reason:
function the_producers($post_id = false) {
if ($post_id == false) {
$post_id = get_the_ID();
}
$producers = get_the_terms($post_id, 'producers');
$prods = array();
$cnt = 0;
foreach ($producers as $producer) {
$cnt++;
$prods[] = $producer->name;
}
if ($cnt == 1) {
$str = $producer->name;
} else {
$str = array_pop($prods);
if ($prods) {
$str = implode(', ', $prods).' & '.$str;
return $str;
} else {
return false;
}
}
}