繁体   English   中英

WordPress选项页面和回调函数循环

[英]Wordpress options page and looping through callback functions

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

我假设有一种更优雅的方法来执行此操作,因为当它们实质上相同时,单独创建所有回调将是非常多余的。

解决方法如下:

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] . "' />";
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM