添加设置
您必须使用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( string $option, mixed $default = false );
获取设置是通过get_option()函数完成的。
该函数接受两个参数:选项的名称和该选项的可选默认值。
实例
// Get the value of the setting we've registered with register_setting() $setting = get_option('wporg_setting_name');