我有以下代码,它是小部件的一部分,输出分类法“季节”的条款
分类术语在它们之间以空格和逗号输出,但它也在最后添加逗号。
我该如何摆脱最后一个逗号?
echo $args['before_widget'];
if ( ! empty( $title ) )
echo $args['before_title'] . $title . $args['after_title'];
global $post;
$tags = get_the_terms( $post->ID, 'season' );
if( $tags ) : ?>
<?php foreach( $tags as $tag ) :
$tag_link = esc_url( get_term_link( $tag ) );
$tag_output = '';
$tag_output .= '<a href="' . $tag_link . '" class="listing-tag">';
$tag_output .= '<span class="tag__text">' . $tag->name . '</span></a>';
$tag_output .=", ";
echo $tag_output;
endforeach; ?>
<?php endif;
echo $args['after_widget'];
}
我试图使用rtrim($tag_output,', ');
但我无法弄清楚在哪里放置这个rtrim
字符串,以使其工作。
代码中的哪个位置rtrim($tag_output,', ');
应该让这个工作?
map your array可能更容易包含你想要的字符串,然后使用implode()
显示它。例如
if ($tags) {
$tagOutput = array_map(function($tag) {
return sprintf(
'<a href="%s" class="listing-tag"><span class="tag__text">%s</span></a>',
esc_url( get_term_link( $tag ) ),
$tag->name
);
}, $tags);
echo implode(', ', $tagOutput);
}
echo $args['after_widget'];