【问题标题】:Wordpress: Removing the last comma for tag listWordpress:删除标签列表的最后一个逗号
【发布时间】:2010-08-12 19:05:04
【问题描述】:

我创建了一个自定义的 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>, ';
    }
}
?>

【问题讨论】:

  • 如果不是问题的原始代码,除了 Jan Fabry 之外,没有人会费心正确缩进他们的答案吗? (我现在很礼貌地进行缩进。)

标签: php wordpress tags


【解决方案1】:

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

【讨论】:

  • 这会在正确提供标签信息之前多次输出博客的 url。还是要知道的好功能!谢谢!
  • @bookmark:我更新了我的示例以使用get_tag_link 而不是自己构建链接,这将始终使用正确的格式。我添加了一个我之前使用的“奖励”功能,以获得更好的输出。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    试试这样的?

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

    【讨论】:

    • 这是所有建议中较长的代码,但这是我理解的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多