在WordPress短代码中,如何传递布尔属性?
这两个[shortcode boolean_attribute="true"]或者[shortcode boolean_attribute=true]是给字符串值。
编辑
如果我使用@brasofilo评论的技巧,知道他们在做什么的用户将没有问题。但是,如果某些用户提供属性false值并获得true值,他们将会迷路。那么还有其他解决方案吗?
在WordPress短代码中,如何传递布尔属性?
这两个[shortcode boolean_attribute="true"]或者[shortcode boolean_attribute=true]是给字符串值。
编辑
如果我使用@brasofilo评论的技巧,知道他们在做什么的用户将没有问题。但是,如果某些用户提供属性false值并获得true值,他们将会迷路。那么还有其他解决方案吗?
Answers:
易于使用0和1值,然后在函数内部进行类型转换:
[shortcode boolean_attribute='1'] 要么 [shortcode boolean_attribute='0']
但是如果您愿意,也可以严格检查'false'并将其分配给boolean,这样您还可以使用:
[shortcode boolean_attribute='false'] 要么 [shortcode boolean_attribute='true']
然后:
add_shortcode( 'shortcode', 'shortcode_cb' );
function shortcode_cb( $atts ) {
extract( shortcode_atts( array(
'boolean_attribute' => 1
), $atts ) );
if ( $boolean_attribute === 'false' ) $boolean_attribute = false; // just to be sure...
$boolean_attribute = (bool) $boolean_attribute;
}
'true'和'false'
作为@GM答案的扩展(这是实现此目标的唯一方法),以下是略微简化/美化的扩展版本(我个人更喜欢):
boolean检查包含的值就足够了。如果为true,则结果为(bool) true,否则为false。这产生一个情况true,其他所有false结果。
add_shortcode( 'shortcodeWPSE', 'wpse119294ShortcodeCbA' );
function wpse119294ShortcodeCbA( $atts ) {
$args = shortcode_atts( array(
'boolAttr' => 'true'
), $atts, 'shortcodeWPSE' );
$args['boolAttr'] = 'true' === $args['boolAttr'];
}
我之所以喜欢此版本,是因为它允许用户输入on/yes/1的别名true。当用户不记得实际值true是多少时,这会减少用户出错的机会。
add_shortcode( 'shortcodeWPSE', 'wpse119294ShortcodeCbA' );
function wpse119294ShortcodeCbA( $atts ) {
$args = shortcode_atts( array(
'boolAttr' => 'true'
), $atts, 'shortcodeWPSE' );
$args['boolAttr'] = filter_var( $args['boolAttr'], FILTER_VALIDATE_BOOLEAN );
}
1)始终传递的第3个参数shortcode_atts()。否则,无法定位简码属性过滤器。
// The var in the filter name refers to the 3rd argument.
apply_filters( "shortcode_atts_{$shortcode}", $out, $pairs, $atts );
2)切勿使用extract()。甚至core都希望减少这些呼叫。同样,global变量也更糟,因为IDE不能解决提取的内容,并且会抛出故障消息。
wp_validate_boolean()WordPress 4.0.0或更高版本中的函数有助于验证布尔值。函数参考developer.wordpress.org/reference/functions/wp_validate_boolean
filter_var( $var, FILTER_VALIDATE_BOOLEAN ).,甚至该函数的docblock本身也说明。
false,否则true。