开发者

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>, ';
    }
}
?>


implode is your friend, if you don't want to be Shlemiel the painter.

$posttags = get_the_tags();
if ($posttags) {
   $tagstrings = array();
   foreach($posttags as $tag) {
      $tagstrings[] = '<a href="' . get_tag_link($tag->term_id) . '" class="tag-link-' . $tag->term_id . '">' . $tag->name . '</a>';
   }
   echo implode(', ', $tagstrings);
}

// For an extra touch, use this function instead of `implode` to a better formatted string
// It will return "A, B and C" instead of "A, B, C"
function array_to_string($array, $glue = ', ', $final_glue = ' and ') {
    if (1 == count($array)) {
        return $array[0];
    }
    $last_item = array_pop($array);
    return implode($glue, $array) . $final_glue . $last_item;
}


You could do it with rtrim.

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


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 ;
}
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜