問題描述
在 WordPress 短碼中,我如何傳遞布林屬性? [shortcode boolean_attribute="true"]或 [shortcode boolean_attribute=true]都提供字串值。
編輯
如果我使用 @brasofilo 評論的伎倆,知道他們正在做什麼的使用者將沒有問題。但是如果一個使用者給出了一個屬性 false 的值並且接收到 true 的值,一些使用者就會丟失。那麼還有其他解決方案嗎?
最佳解決方案
很容易使用 0 和 1 值,然後在型別轉換內的功能:
[shortcode boolean_attribute='1']或 [shortcode boolean_attribute='0']
但是如果你想要也可以嚴格檢查'false'並將其分配給布林值,這樣也可以使用:
[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;
}
次佳解決方案
作為 @ G.M 的擴充套件。答案 (這是唯一可能的方法),這裡稍微縮短/美化和擴充套件版本 (我個人更喜歡):
縮短/美化變體
對 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'];
}
擴充套件/User-safe 變體
我喜歡這個版本的原因是它允許使用者輸入 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) 始終透過 shortcode_atts()的第三個引數。否則,短碼屬性過濾器是不可能的目標。
// The var in the filter name refers to the 3rd argument.
apply_filters( "shortcode_atts_{$shortcode}", $out, $pairs, $atts );
2) 切勿使用 extract()。即使是核心想減少這些電話。 global 變數同樣更糟,因為 IDE 不能有機會解析提取的內容,並會丟失失敗訊息。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。