我有一个小片段用于在WordPress中显示用逗号分隔的标签:
<?php
$tags = get_tags();
$html = '<div class="post_tags">';
foreach ( $tags as $tag ) {
$tag_link = get_tag_link( $tag->term_id );
$html .= "<a href='{$tag_link}' title='{$tag->name} Tag' class='{$tag->slug}'>";
$html .= "{$tag->name}</a>, ";
}
$html .= '</div>';
echo $html;
?>
现在,如何删除最后一个逗号?或者也许有比上面更好的方式?
答案 0 :(得分:0)
<?php
$tags = get_tags();
$tag_count = 1;
$html = '<div class="post_tags">';
foreach ( $tags as $tag ) {
$tag_link = get_tag_link( $tag->term_id );
$html .= "<a href='{$tag_link}' title='{$tag->name} Tag' class='{$tag->slug}'>";
$html .= "{$tag->name}</a>" . ( $tag_count < count( $tags ) ? ", " : "");
$tag_count++;
}
$html .= '</div>';
echo $html;
?>
如果标签总数小于当前计数,您只需设置计数并显示逗号。一旦计数等于标签总数,它将不显示任何内容而不是逗号。
答案 1 :(得分:0)
或者,如果你不想在循环中反复计数。
<?php
$tags = get_tags();
$arr_len = count($tags); // Performance matter
$html = '<div class="post_tags">';
foreach ($tags as $index => $tag) {
$tag_link = get_tag_link( $tag->term_id );
$html .= "<a href='{$tag_link}' title='{$tag->name} Tag' class='{$tag->slug}'>";
$html .= "{$tag->name}</a>" . ( ($index == $arr_len - 1) ? '' : ', ');
}
$html .= '</div>';
echo $html;
?>