问题描述
我正在尝试创建一个短代码来输出我的自定义分类法,用逗号分隔,但我希望最后一个逗号是“en”而不是逗号。像这样:
到目前为止我有这个:
// Assortiment shortcode
function verlichting_type( ){
$terms = get_the_terms( $post->ID,'verlichting_type' );
foreach($terms as $term) {
$entry_terms .= $term->name . ',';
}
$entry_terms = rtrim( $entry_terms,',' );
return '<span class="verlichting__type"> ' . $entry_terms . ' </span>';
}
add_shortcode( 'verlichting_type','verlichting_type' );
解决方法
WordPress 已经有自定义的 printf 函数可以本地化输出
因此,如果您的网站语言是法语,则意味着
wp_sprintf_l( '%l',['Hello','world','never','give','up'] )
上面的代码会输出
Hello,world,never,give,et up
西班牙语:
Hello,give y up
正如您所指出的,根据语言,将添加/删除最后一个逗号
,由于我没有 $terms
或 $entry_terms
变量的示例,因此我不得不编写一些虚拟数据,但我认为您应该能够提取我的示例并将其放入您的代码中。
我使用了三元运算符 (https://www.php.net/manual/en/language.operators.comparison.php) 来确定最后一个逗号应该是 ',' 还是 'en':
<?php
function verlichting_type() {
$entry_terms = "";
$terms = [
(object)['name' => 'taxonomy'],(object)['name' => 'taxonomy'],(object)['name' => 'taxonomy']
];
echo '<span class="verlichting__type">';
foreach ( $terms as $index => $term) {
$enIndex = sizeof($terms) - 2;
$end = (isset($terms[$enIndex]) && $index == $enIndex ? ' en ' : ',');
$entry_terms .= $term->name . $end;
}
$entry_terms = rtrim( $entry_terms,',' );
return $entry_terms . '</span>';
}
输出:
<span class="verlichting__type">taxonomy,taxonomy,taxonomy en taxonomy</span>
这应该适用于任何数组长度,例如如果 $terms
只有 2 个元素:
<span class="verlichting__type">taxonomy en taxonomy</span>
或 1 个元素:
<span class="verlichting__type">taxonomy</span>