【问题标题】:Wordpress options page and looping through callback functionsWordpress 选项页面和循环回调函数
【发布时间】:2012-05-31 11:54:09
【问题描述】:

我正在创建一个简单的 Wordpress 插件,它将在设置菜单中设置一个选项页面,客户可以在其中添加他们的业务详细信息。

我将所有字段注册到:

// Lets set an array for the inputs:
   $fields = array (
       array( "name",           "Business Name:"),
       array( "tagline",        "Business Tagline:"),
       array( "logo",           "Business Logo:"),
       array( "owner_name",     "Owner's Name:"),
       array( "owner_title",    "Owner's Title"),
       array( "address",        "Address:"),
       array( "city",           "City:"),
       array( "province",       "Province:"),
       array( "country",        "Country:"),
       array( "phone",          "Phone:"),
       array( "secondary_phone","Secondary Phone:"),
       array( "fax",            "Fax:"),
       array( "toll_free",      "Toll Free:"),
       array( "email",          "Email:"),
       array( "website",        "Website:"),
   );

   foreach($fields as $field) {
       //id, title (label), callback, page, section(from add_settings_section), args
       add_settings_field("business_{$field[0]}", $field[1], "business_{$field[0]}_setting", __FILE__, 'main_section');
   }

这只是循环遍历数组中的设置,添加我需要的所有字段,并使用business_{$field[0]}_setting 设置对回调函数的引用。

然后我必须为每个函数创建回调函数,例如:

function business_name_setting() {
  $options = get_option('plugin_options');  
  echo "<input name='plugin_options[business_name]' type='text' value='{$options['business_name']}' />";
}

我假设有一种更优雅的方法可以做到这一点,因为当它们基本上相同时单独创建所有回调将是非常多余的。

【问题讨论】:

    标签: php wordpress foreach settings admin


    【解决方案1】:

    解决方法如下:

    add_settings_field 函数采用第 6 个参数,将其传递给回调函数。我已将$field[0] 的值发送给它。我还设置了add_settings_field 函数将所有回调发送到现在称为business_setting 的处理函数。

    新的 foreach 循环:

    foreach($fields as $field) {
           //id, title (label), callback, page, section(from add_settings_section), args
           add_settings_field("business_{$field[0]}", $field[1], "business_setting", __FILE__, 'main_section', $field[0]);
       }
    

    新的回调函数,现在通过我们之前的$field[0] 值,现在可以使用该键来创建正确的输入:

    function business_setting($field) {
      $options = get_option('plugin_options'); 
      $full_field = 'business_'.$field;
      echo "<input name='plugin_options[{$full_field}]' type='text' value='" . $options[$full_field] . "' />";
    }
    

    【讨论】:

      猜你喜欢
      • 2021-07-02
      • 1970-01-01
      • 2013-12-11
      • 2017-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      相关资源
      最近更新 更多