我正在创建一个简单的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']}' />";
}
我假设有一种更优雅的方式来做到这一点,因为当它们基本上是相同的时候单独创建所有回调将是非常多余的。
答案 0 :(得分: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] . "' />";
}