問題描述

在一個外掛類中,我想為公共資料提供簡單的欄位:電子郵件,電話號碼,Twitter 等。列表可以擴充套件。

有關詳細資訊,請參閱 GitHub 上的 plugin Public Contact Data

為了保持簡單的使用,我也想提供一些易於輸入的短碼:

  • [public_email]

  • [public_phone]

  • [public_something]

唯一的區別是第二部分。我不想要更多的引數,因為它們是容易出錯的。所以我為我的外掛類中的所有欄位註冊一個短碼處理程序:

foreach ( $this->fields as $key => $value )
{
    add_shortcode( 'public_' . $key, array( $this, 'shortcode_handler' ) );
}

現在 shortcode_handler()必須知道哪個短碼被稱為。我的問題是:我該怎麼做?

我目前的解決方法是另一個功能:

protected function current_shortcode()
{
    $backtrace = debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS );
    return $backtrace[3]['args'][0][2];
}

這… 適用於 the_content()。但它既不優雅也不健壯。我已經讀過 wp-includes/shortcodes.php,但是我現在看不到如何做得更好。

最佳解決方案

這是未經測試的,但是回撥函式提供了一個引數陣列 $args,它給出 (如果有的話) 提供 shortocode 的引數。第零個條目有時包含使用的短碼的名稱 (例如 public_email) 。有時我的意思是

The zeroeth entry of the attributes array ($atts[0]) will contain the string that matched the shortcode regex, but ONLY if that differs from the callback name, which otherwise appears as the third argument to the callback function.

(見 Codex) 。為了您的目的,$atts[0]將包含 public_emailpublic_phone 等。

function shortcode_handler($atts,$content=NULL){
     if(!isset($atts[0]))
         return; //error?

     switch($atts[0]):
         case 'public_email':
              //deal with this case
              break;
         case 'public_phone':
              //deal with this case
              break;
         case 'public_something':
              //deal with this case
              break;
     endswitch;
}

參考文獻

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