php - Using 'and' before the last value in get_the_term_list in Wordpress
Is there a way to use the word 'and' in the output of get_the_term_list?
<?php echo strip_tags(get_the_term_list( $post->ID, 'stijl', ' ',', ')); ?>
This code results in this output:
Onverwachte wending, Pakkend, Slasher, Slim, Spanning
But i want it to be:
Onverwachte wending, Pakkend, Slasher, Slim and Spanning
So basically i want the last comma to turn into 'and'. Got no clue how to accomplish this. Is it even possible?
Answer
Solution:
In WordPress, get_the_term_list
returns a formatted version of get_the_terms
,
which returns an array of the terms on the post. We can use this to customize the format of the list.
Typically when I do this I add something like the following to functions.php:
// In functions.php
function so_63957175_niceTermList($taxonomy = 'category') {
global $post;
$term_list = '';
$terms = get_the_terms($post->ID, $taxonomy);
$n = 1;
if ($terms) {
foreach($terms as $term) {
if ($n < count($terms)) {
$term_list .= $term->name . ', ';
} else {
$term_list = rtrim($term_list, ', ') . ' and ' . $term->name;
}
++$n;
}
}
$term_list = rtrim($term_list, ', ');
return $term_list;
}
// In your template file
<?php echo so_63957175_niceTermList('category'); ?>
Source