Wordpress - 使用 rtrim 从输出中删除最后一个逗号
Wordpress - remove last Comma from output with rtrim
我有以下代码,它是输出分类术语的小部件的一部分 'season'
分类术语以 space 和逗号之间的逗号输出,但它还在最后添加了一个逗号。
如何去掉最后一个逗号?
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 to one containing the strings you want and then display it using 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'];
我有以下代码,它是输出分类术语的小部件的一部分 'season'
分类术语以 space 和逗号之间的逗号输出,但它还在最后添加了一个逗号。
如何去掉最后一个逗号?
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 to one containing the strings you want and then display it using 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'];