组合简码并以全部大写形式打印包含 3 个或更少字母的所有单词

问题描述 投票:0回答:1

我尝试组合我的短代码:

add_shortcode( 'MARKE', 'marke_shortcode' );
function marke_shortcode() {
    $terms = get_the_terms( get_the_ID(), 'marken');
    return ucwords($terms[1]->slug);
}

使用我在这里找到的代码:https://stackoverflow.com/a/4977241/20149572

现在我明白了,但它似乎不起作用。我错过了什么?

add_shortcode( 'MARKE', 'marke_shortcode' );
function marke_shortcode() {
    $terms = get_the_terms( get_the_ID(), 'marken');
    $array = explode(' ', $terms);
    foreach($array as $k => $v) {
        if(strlen($v) <= 3) {
            $array[$k] = strtoupper($v); //completely upper case
        }
        else {
            $array[$k] = ucfirst($v); //only first character upper case
        }
    }
    $string = implode(' ', $array); 
    return $array;
}
php wordpress shortcode uppercase
1个回答
0
投票

$terms
已经是一个数组,所以你不需要这一行:

$array = explode(' ', $terms);

尝试删除此代码片段。

add_shortcode( 'MARKE', 'marke_shortcode' );
function marke_shortcode() {
    $arr = [];
    $terms = get_the_terms( get_the_ID(), 'marken');

    foreach($terms as $k => $v) {
        $term_name = $v->name;

        if(strlen($term_name) <= 3) {
            $arr[$k] = strtoupper($term_name); //completely upper case
        } else {
            $arr[$k] = ucfirst($term_name); //only first character upper case
        }
    }
    
    $string = implode(' ', $arr); 
    
    return $string;
}

您还可以使用

array_map
作为替代选项:

add_shortcode( 'MARKE', 'marke_shortcode' );
function marke_shortcode() {
    $terms = get_the_terms( get_the_ID(), 'marken');

    $arr = array_map(function($v){
        $term_name = $v->name;
        return strlen($term_name) < 4 ? strtoupper($term_name) : ucfirst($term_name);
    }, $terms);
    
    return implode(' ', $arr);
}
© www.soinside.com 2019 - 2024. All rights reserved.