Search code examples
phpwordpresstags

Wordpress: Removing the last comma for tag list


I've created a custom foreach output that helps give me a tag id per post. I'm using commas to separate each tag. However, the last tag outputs a comma too, like this:

kittens, dogs, parrots, (<-- last comma)

How should I go about revising the foreach output so that the last comma is removed so it displays like this:

kittens, dogs, parrots

Here's the code:

<?php
$posttags = get_the_tags();
if ($posttags) {
    foreach($posttags as $tag) {
        echo '<a href="';
        echo bloginfo(url);
        echo '/?tag=' . $tag->slug . '" class="tag-link-' . $tag->term_id . '">' . $tag->name . '</a>, ';
    }
}
?>

Solution

  • Try something like this?

    <?php
    $posttags = get_the_tags();
    if ($posttags) {
        $loop = 1; // *
        foreach($posttags as $tag) {
            echo '<a href="';
            echo bloginfo(url);
            if ($loop<count($posttags)) $endline = ', '; else $endline = ''; // *
            $loop++ // *
            echo '/?tag=' . $tag->slug . '" class="tag-link-' . $tag->term_id . '">' . $tag->name . '</a>' . $endline;
        }
    }
    ?>
    

    edit or

    <?php
    $posttags = get_the_tags();
    if ($posttags) {
        $tagstr = '';
        foreach($posttags as $tag) {
            $tagstr .= '<a href="';
            $tagstr .= bloginfo(url);
            $tagstr .= '/?tag=' . $tag->slug . '" class="tag-link-' . $tag->term_id . '">' . $tag->name . '</a>';
        }
        $tagstr = substr($tagstr , 0, -2);
        echo $tagstr ;
    }
    ?>