Wordpress: How to add commas in this get_the_terms function
Instead of echoing all the variables during your loop, you should store them all to an array and then use the implode()
function to echo them all with the formatting you desire.
// Get terms for post
$terms = get_the_terms($post->ID, 'skills');
if($terms != null) {
$output = array();
foreach($terms as $term) {
$output[] = $term->name;
unset($term);
}
echo implode(", ", $output)
}
Don't want to use an array or variable? There is another solution. Just check if you are currently on the very last element in the array during your loop.
// Get terms for post
$terms = get_the_terms($post->ID, 'skills');
if($terms != null) {
end($terms);
$endKey = key($terms);
foreach($terms as $key => $term) {
echo $key != $endKey? $term->name.", " : $term->name;
unset($term);
}
}
I added $key
to the foreach loop so you can compare against that. You can get the final key of the array by doing end($array)
and then using key()
to get the actual key.