使用设置 API
添加设置
您必须使用register_setting()定义新设置,它将在{$wpdb->prefix}_options
表中创建一个条目。
您可以使用add_settings_section()在现有页面上添加新部分。
您可以使用add_settings_field()将新字段添加到现有部分。
添加设置
register_setting(
string $option_group,
string $option_name,
callable $sanitize_callback = ''
);
请参阅有关register_setting()的函数参考 以获取有关所使用参数的完整说明。
添加一个部分
add_settings_section(
string $id,
string $title,
callable $callback,
string $page
);
部分是您在 WordPress 设置页面上看到的具有共享标题的设置组。在您的插件中,您可以向现有设置页面添加新部分,而不是创建一个全新的页面。这使得您的插件更易于维护,并创建更少的新页面供用户学习。
有关所用参数的完整说明,请参阅有关add_settings_section()的函数参考。
添加字段
add_settings_field(
string $id,
string $title,
callable $callback,
string $page,
string $section = 'default',
array $args = []
);
有关所用参数的完整说明,请参阅有关add_settings_field()的函数参考。
例子
function wporg_settings_init() {
// register a new setting for "reading" page
register_setting('reading', 'wporg_setting_name');
// register a new section in the "reading" page
add_settings_section(
'wporg_settings_section',
'WPOrg Settings Section', 'wporg_settings_section_callback',
'reading'
);
// register a new field in the "wporg_settings_section" section, inside the "reading" page
add_settings_field(
'wporg_settings_field',
'WPOrg Setting', 'wporg_settings_field_callback',
'reading',
'wporg_settings_section'
);
}
/**
* register wporg_settings_init to the admin_init action hook
*/
add_action('admin_init', 'wporg_settings_init');
/**
* callback functions
*/
// section content cb
function wporg_settings_section_callback() {
echo '<p>WPOrg Section Introduction.</p>';
}
// field content cb
function wporg_settings_field_callback() {
// get the value of the setting we've registered with register_setting()
$setting = get_option('wporg_setting_name');
// output the field
?>
<input type="text" name="wporg_setting_name" value="<?php echo isset( $setting ) ? esc_attr( $setting ) : ''; ?>">
<?php
}
获取设置
获取设置是通过get_option() 函数完成的。
该函数接受两个参数:选项的名称和该选项的可选默认值。
例子
// Get the value of the setting we've registered with register_setting()
$setting = get_option('wporg_setting_name');
无评论