我尝试组合我的短代码:
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;
}
$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);
}
大部分代码都可以合并。另请参阅问题正文中链接的页面上我的新答案。
就像 @mikerojas 已经提到的那样,看起来您未能从
slug
返回的数组中分离出 get_the_terms()
列值。
当将数组传递给
preg_replace_callback()
时,将返回一个数组。
精炼后的脚本现在只声明临时变量
$m
;其他处理都是嵌套的,所以可以直接返回最终的结果字符串。
代码:
add_shortcode('MARKE', 'marke_shortcode');
function marke_shortcode() {
return implode(
' ',
preg_replace_callback(
'/\b\w(?:\w{1,2}\b)?/',
fn($m) => strtoupper($m[0]),
array_column(get_the_terms(get_the_ID(), 'marken'), 'slug')
)
);
}