問題描述

食典説

shortcode_atts() combines user shortcode attributes with known attributes and fills in defaults when needed. The result will contain every key from the known attributes, merged with values from shortcode attributes.

對我來説沒什麼意義 (我是新手) 。

這是一個例子:

function wps_trend($atts) {
extract( shortcode_atts( array(
'w' => '500',
'h' => '330',
'q' => '',
'geo' => 'US',
), $atts));
$h = (int) $h;
$w = (int) $w;
$q = esc_attr($geo);
ob_start();

請你解釋一下

最佳解決方案

shortcode_atts()類似於 array_merge():它將第二個參數列表合併到第一個。區別是:它僅合併第一個參數 ($default) 中存在的鍵。

extract()然後獲取數組鍵,將其設置為變量名稱,並將其值作為變量值。 'w' => '500'在您的例子中成為 $w = '500'

不要使用 extract()。這個非常糟糕的代碼風格。它的用法是 deprecated even in core,這意味着什麼… 🙂

你的例子應該寫成:

$args = shortcode_atts(
    array(
        'w'   => '500',
        'h'   => '330',
        'q'   => '',
        'geo' => 'US',
    ),
    $atts
);
$w = (int) $args['w'];
$h = (int) $args['h'];
$q = esc_attr( $args['q'] );

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。