Wordpress:删除标记列表的最后一个逗号

时间:2010-08-12 19:05:04

标签: php wordpress tags

我创建了一个自定义foreach输出,它有助于为每个帖子提供一个标记ID。我用逗号分隔每个标签。但是,最后一个标记也输出一个逗号,如下所示:

小猫,狗,鹦鹉,(< - 最后一个逗号)

我应该如何修改foreach输出,以便删除最后一个逗号,使其显示如下:

小猫,狗,鹦鹉

以下是代码:

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

3 个答案:

答案 0 :(得分:4)

implode是您的朋友,如果您不想成为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;
}

答案 1 :(得分:1)

尝试这样的事情?

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

修改

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

答案 2 :(得分:1)

您可以使用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, ', ');
}
?>