Wordpress 分类法最后一个 child 由 "en" 而不是逗号分隔

Wordpress taxonomy last child separated by "en" instead of comma

我正在尝试创建一个短代码来输出我的自定义分类法,用逗号分隔,但我希望最后一个逗号是“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' );

因为我没有 $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'],
        (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>

WordPress 已经有自定义 printf 函数,可以本地化输出

因此,如果您的网站语言是法语,则意味着

wp_sprintf_l( '%l', ['Hello', 'world', 'never', 'give', 'up'] )

以上代码会输出

Hello, world, never, give, et up

对于西班牙语:

Hello, world, never, give y up

正如您根据语言指出的那样,最后一个逗号将是 added/removed