2010-08-12 113 views
0

我创建了一个自定义的foreach输出,帮助给我每个职位的标记ID。我使用逗号分隔每个标签。然而,最后的标签输出一个逗号太多,像这样:WordPress的:删除标记列表的最后一个逗号

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

我应该如何着手,这样最后一个逗号被删除修改的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>, '; 
    } 
} 
?> 
+1

没有人可以,但如果不是问题的原始代码,Jan Fabry甚至会打扰他们的答案吗? (我现在礼貌地做了缩进。) – BoltClock 2010-08-12 19:41:56

回答

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

这是所有建议中较长的代码,但它是我理解的。谢谢! – 2010-08-13 22:53:31

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

这会在标记信息正确输出之前多次输出博客的url。仍然是一个很好的功能知道!谢谢! – 2010-08-13 22:51:55

+0

@bookmark:我更新了我的示例以使用['get_tag_link'](http://codex.wordpress.org/Function_Reference/get_tag_link)而不是自己构建链接,它将始终使用正确的格式。我添加了一个我以前用过的“奖励”功能,以获得更好的输出。 – 2010-08-14 07:14:30

+0

太热了,收藏了!谢谢! – 2010-08-14 21:17:16

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