wordfool
wordfool

Reputation: 63

add commas to wordpress-generated list

I have a small function that modifies links created by the Wordpress get_the_term_list function but cannot work out how to add commas (or another separator) between list items. My attempt adds commas but also adds one at the end of the list, which I don't want. How do I remove that last comma?

$terms = strip_tags( get_the_term_list( $post->ID, 'portfolio_cat', '', '/' ));
$terms = explode("/",$terms);
for($i=0; $i<count($terms); $i++){ 
echo "<a href='urlhere/$terms[$i]'>" . $terms[$i] . "</a>";
$total = count($terms);
if ($i != $total) echo', ';
}

Upvotes: 0

Views: 280

Answers (1)

rnevius
rnevius

Reputation: 27102

You're close...but the issue is because you're starting $i at 0, and count() starts at 1. So, to fix the issue, just add a -1 to your total:

$terms = strip_tags( get_the_term_list( $post->ID, 'portfolio_cat', '', '/' ));
$terms = explode("/",$terms);

for($i=0; $i<count($terms); $i++){ 
    echo "<a href='urlhere/$terms[$i]'>" . $terms[$i] . "</a>";
    $total = count($terms) - 1;

    if ($i != $total) { echo', '; }
}

Upvotes: 1

Related Questions