0

我正在创建一个简单的 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']}' />";
}

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

4

1 回答 1

0

解决方法如下:

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] . "' />";
}
于 2012-05-24T21:40:44.370 回答