2017-10-04 57 views
0

我正在開發一個簡單的基於插件的自定義帖子類型。帖子類型已註冊正常。現在我想創建一些元框並通過回調參數傳遞一些屬性值。這是我的嘗試:WordPress:無法訪問回調函數內部的callback_args鍵值

function wpcd_add_dealer_meta_boxes() { 
     add_meta_box(
      'dealer_first_name', 
      'First Name', 
      array($this, 'wpcd_meta_box_first_name_markup'), 
      'dealers', 
      'normal', 
      'default', 
      array(
       'id' => 'first_name', 
       'name' => 'first_name', 
       'type' => 'text', 
       'placeholder' => 'Enter first name', 
       'maxlength' => '30', 
       'spellcheck' => 'true', 
       'autocomplete' => 'off' 
      ) 
     ); 
    } 

這裏是我的參數回調函數:

function wpcd_meta_box_first_name_markup($args) { 
     $html = '<input '; 
     $html.= 'type="' . $args->type . '" '; 
     $html.= 'id="' .$args->id . '" '; 
     $html.= 'name="' .$args->name . '" '; 
     if(isset($args->required) && ($args->required == 'true' || $args->required == '1')) { 
      $html.= 'required '; 
     } 

     if(isset($args->placeholder) && $args->placeholder != '') { 
      $html.= 'placeholder="' . esc_attr($args->placeholder) . '" '; 
     } 

     if(isset($args->maxlength)) { 
      $html.= 'maxlength="' . $args->maxlength . '" '; 
     } 

     if(isset($args->spellcheck) && ($args->spellcheck == 'true')) { 
      $html.= 'spellcheck="' . $args->spellcheck . '" '; 
     } 

     if(isset($args->autocomplete) && ($args->autocomplete == 'on')) { 
      $html.= 'autocomplete="' . $args->autocomplete . '" '; 
     } 

     $html.= '/>'; 

     echo $html; 
    } 

但我不能得到像$args->id, $args->name等函數內部的值。確切地說,所有的值都是空的,我沒有檢查if(isset(...))。而我所做的那些都被忽略了。

用我的上述代碼我期待以下標記作爲輸出:

<input type="text" id="first_name" name="last_name" required placeholder="Enter firstname" maxlength="30" autocomplete="off" spellcheck="true" /> 

而實際輸出是

<input type="" id="" name="" /> 

屬性typeidname不包裹一個if(isset())塊內部,從而它們正在生成(具有空值)以及包含在if(isset())塊中的任何內容,都被簡單地忽略,就好像它們沒有設置一樣!

我失蹤或做錯了什麼? 任何建議對我來說都是救命的。

+1

有關使用'的$ args [ '型']'等什麼? – Und3rTow

+0

確實。您將值放入數組中並使用對象訪問語法來嘗試將其排除。 –

+0

@ Und3rTow我試過'$ args ['type']'已經得到了這個: '致命錯誤:不能使用WP_Post類型的對象作爲/var/www/wp-projects/subratasarkar.com/wp-content中的數組/plugins/product-dealer/product-dealer.php on line 68' @MattGibson請問您正確的做法嗎? –

回答

2

如果你仔細檢查documentation for add_meta_box(),你會看到:傳遞給你的回調

($callback_args (array) (Optional) Data that should be set as the $args property of the box array (which is the second parameter passed to your callback).

第一參數是WP_Post對象。 第二個是您的參數數組。因此,嘗試:

function wpcd_meta_box_first_name_markup($post, $args) { ... 

,然後訪問你的論點,你會期望:

$args['type'] 
+0

是的,我終於搞定了。我錯過了第一個參數'$ post'。然後使用var_dump我知道數組是如何形成的。對不起,先生。非常感謝您的關注。 –

相關問題