这里公认的答案是对的和错的。短语:
“WordPress放弃任何未给定默认值的ATT”
仅为trueshortcode_atts 功能,而不是整个WP短代码功能。
如果查看以下代码:
add_shortcode( \'paragraph\', \'custom_shortcode_paragraph\' );
function custom_shortcode_paragraph( $atts ) {
// Attribute Defaults Function
$atts = shortcode_atts(
array(
\'last\' => false,
),
$atts
);
$isLast = $atts[\'last\'] !== false;
}
短代码用法如下
[paragraph last] something [/paragraph] 将始终具有值
false 对于
$isLast 变量。
问题是shortcode_atts 函数运行时,会丢弃没有值的属性。然而,他们绝对处于$atts 但在该点之前排列。A.var_dump 属于$atts 作为custom_shortcode_paragraph 功能将产生:
array(1) {
[0]=>
string(4) "last"
}
所以
0th 数组中的项是强制为小写的属性名称字符串。
让我们将代码改为以下内容:
add_shortcode( \'paragraph\', \'custom_shortcode_paragraph\' );
function custom_shortcode_paragraph( $atts ) {
// look for the existance of the string \'last\' in the array
$last = in_array(\'last\', $atts); // $last is now a boolean
// Attribute Defaults Function
$atts = shortcode_atts(
array(
\'last\' => $last, // default to true if the attribute existed valueless
),
$atts
);
$isLast = $atts[\'last\'] !== false;
}
你现在有
$atts[\'last\'] === true && $isLast === true 对于短代码:
[paragraph last] something [/paragraph]
如果您最终添加了一个值,则短代码:
[paragraph last="any value at all"] something [/paragraph]
会吗
$atts[\'last\'] === "any value at all" && $isLast === true.
$last 可能是
false 因为
$atts 开头的数组包含以下内容:
array(1) {
["last"]=>
string(16) "any value at all"
}
因此,数组项的值不再是属性名和
in_array(\'last\', $atts) === false 因此,默认值为
shortcode_atts 这是错误的。但这只是一个默认值,被
any value at all 然后
$atts[\'last\'] !== false 是
true 因为
"any value at all" !== false.
综上所述,我认为这可以满足您的需要,并且能够抵御用户错误。