WordPress插件开发教程手册 — 设置选项

为了使管理界面易于构建,安全,并在设计上和 WordPress 管理界面保持一致,WordPress 提供了两个核心 API。

设置

设置 API 侧重于为我们提供了一种创建表单和管理表单数据的方式。选项 API 侧重于为我们提供一种简单的键/值系统来管理数据。

快速参考

请参阅使用设置 API 和选项 API 构建自定义设置页面的完整示例。

设置 API

WordPress 2.7 中增加的设置 API 可以让我们半自动地管理含有设置表单的后台页面,让我们自定义设置页面,以及这些页面中的分节和表单字段。我们可以同时添加新设置页面和与其中的表单字段,也可以添加设置分节和表单字段到现有页面。

开发者依然需要手动注册和验证表单字段,但是设置 API 为我们避免了管理底层选项的大量复杂调试。

使用设置 API 时,接收表单提交的 wp-admin/options.php 页面会进行相当严格的权限检查。用户具有 manage_options 能力才能保存数据。

为什么使用设置 API

我们可以开发自己的设置页面,而不是使用这个 API,这就出现了一个问题,设置 API 可以为我们带来什么好处,以下是一些好处的简要说明。

视觉一致性

使用 API 生成界面元素,可以确保我们的自定义设置页面和 WordPress 默认管理界面一致,如果我们看到了一个风格是 5 年前的设置页面,这个页面肯定没有使用设置 API,如果使用了设置 API,自定义页面的风格会随着 WordPress 默认风格一起更新。所以,使用设置 API 一个很大好处就是,设计页面看起来就像该有的样子(和 WordPress 默认风格一致),感谢 WordPress 的天才设计师们,他们的工作看起来很棒。

健壮性(面向未来)

由于设置API 是 WordPress 核心的一部分,任何更新都将自动更新我们的设置页面,如果我们创建了自己的设置页面,WordPress 的内核更新可能会破坏我们的自定义设置。会有越来越多的开发者测试和维护这些设置 API 代码,所以他们会更加稳定。

工作更轻松

当然,最直接的好处是 WordPress 的设置 API 在底层默默的为我们做了很多工作,以下是一些例子:

  • 处理表单提交 – 让 WordPress 处理并存储 $_POST 提交
  • 包括安全措施 – 可以让我们获得额外的安全措施,如随机数验证
  • 清理数据 – 可以和 WordPress 其他部分一样,自动为我们清理数据,以确保提交的字符串可以安全的使用

函数参考

设置注册/注销注册添加字段/分节
register_setting()
unregister_setting()
add_settings_section()
add_settings_field()
选项表单渲染错误信息
settings_fields()
do_settings_sections()
do_settings_fields()
add_settings_error()
get_settings_errors()
settings_errors()

使用设置 API

添加设置

我们可以使用 register_setting() 来定义一个新的设置,此函数会在 {$wpdb->prefix}_options 数据表中插入一条记录。可以使用 add_settings_section() 在现有设置页面上添加新分节。可以使用 add_settings_field() 将新字段添加到现有的分节上面。

register_setting() 以及所提及的 add_settings_*() 函数都应该添加到 admin_init。

添加设置

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() 的函数参考。

示例

<?php
function wporg_settings_init(){
   // 为 阅读 页面注册新设置
   register_setting('reading', 'wporg_setting_name');

   // 在阅读页面上注册新分节
   add_settings_section(
      'wporg_settings_section',
      'WPOrg Settings Section',
      'wporg_settings_section_cb',
      'reading'
   );

   // 阅读页面中,在 the wporg_settings_section 分节上注册新设置
   add_settings_field(
      'wporg_settings_field',
      'WPOrg Setting',
      'wporg_settings_field_cb',
      'reading',
      'wporg_settings_section'
   );
}
 
/**
 * 注册 wporg_settings_init 到 admin_init Action 钩子
 */
add_action('admin_init', 'wporg_settings_init');
 

/**
 * 回调函数
 */
// 分节内容回调
function wporg_settings_section_cb() {
   echo '<p>WPOrg Section Introduction.</p>';
}
 
// 字段内容回调
function wporg_settings_field_cb() {
   // 获取我们使用 register_setting() 注册的字段的值
   $setting = get_option('wporg_setting_name');
   // 输出字段
   ?>
   <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() 函数可以获取设置数据,该函数接受两个参数:选项的名称和该选项的可选默认值。

示例

// 获取我们上面使用 register_setting() 注册的选项值
$setting = get_option('wporg_setting_name');

选项 API

WordPress 1.0 中引入的选项 API 可以让我们添加、获取、更新和删除 WordPress 选项,结合设置 API,我们可以控制设置页面中的自定义选项。

选项在什么地方保存?

选项存储在 {$wpdb->prefix}_options 数据表中。$wpdb->prefix 由 wp-config.php 配置文件中的 $table_prefix 变量定义。

怎么存储选项?

选项可以以单个值或者数组的形式存储在 WordPress 数据库中。

单个值

保存为单个值的时候,选项值为单个字符串、整数等。

<?php
// add a new option
add_option('wporg_custom_option', 'hello world!');
// get an option
$option = get_option('wporg_custom_option');

数组

保存为数组时,选项值为一个数组。

<?php
// array of options
$data_r = ['title' => 'hello world!', 1, false];
// add a new option
add_option('wporg_custom_option', $data_r);
// get an option
$options_r = get_option('wporg_custom_option');
// output the title
echo esc_html($options_r['title']);

如果我们需要保存大量选项,把这些选项保存为数组,对性能提升可能会有帮助。

当我们单独访问许多选项数据时,可能导致许多单独的数据库事务,通常,数据库事务是昂贵的操作(就时间和服务器资源而言)而把许多选项作为数组存储和获取时,只会产生一个数据库事务,这是一种比较理想的操作。

函数参考

添加选项获取选项更新选项删除选项
add_option()get_option()update_option()delete_option()
add_site_option()get_site_option()update_site_option()delete_site_option()

自定义设置页面

创建自定义设置页面需要用到 创建管理菜单使用设置 API 选项 API 中的相关知识。

请在尝试创建自定义设置页面之前阅读这些章节。

以下示例可以帮助我们快速了解怎么创建自定义设置页面。

创建自定义设置页面的完整示例

下面是创建自定义设置页面的一个完整示例,以下代码中,我们添加了一个名为 WPOrg 的顶级菜单,注册了一个名为 wporg_options 的选项,并使用设置 API 和选项 API 执行了一个 CRUD 增查改删操作(包含显示错误/更新消息)

<?php
/**
 * @internal never define functions inside callbacks.
 * these functions could be run multiple times; this would result in a fatal error.
 */

/**
 * custom option and settings
 */
function wporg_settings_init() {
   // register a new setting for wporg page
   register_setting( 'wporg', 'wporg_options' );

   // register a new section in the wporg page
   add_settings_section(
      'wporg_section_developers',
      __( 'The Matrix has you.', 'wporg' ),
      'wporg_section_developers_cb',
      'wporg'
   );

   // register a new field in the wporg_section_developers section, inside the wporg page
   add_settings_field(
      'wporg_field_pill', // as of WP 4.6 this value is used only internally
      // use $args' label_for to populate the id inside the callback
      __( 'Pill', 'wporg' ),
      'wporg_field_pill_cb',
      'wporg',
      'wporg_section_developers',
      [
         'label_for'         => 'wporg_field_pill',
         'class'             => 'wporg_row',
         'wporg_custom_data' => 'custom',
      ]
   );
}

/**
 * register our wporg_settings_init to the admin_init action hook
 */
add_action( 'admin_init', 'wporg_settings_init' );

/**
 * custom option and settings:
 * callback functions
 */

// developers section cb

// section callbacks can accept an $args parameter, which is an array.
// $args have the following keys defined: title, id, callback.
// the values are defined at the add_settings_section() function.
function wporg_section_developers_cb( $args ) {
   ?>
    <p id=<?php echo esc_attr( $args[ 'id' ] ); ?>><?php esc_html_e( 'Follow the white rabbit.', 'wporg' ); ?></p>
   <?php
}

// pill field cb

// field callbacks can accept an $args parameter, which is an array.
// $args is defined at the add_settings_field() function.
// wordpress has magic interaction with the following keys: label_for, class.
// the label_for key value is used for the for attribute of the <label>.
// the class key value is used for the class attribute of the <tr> containing the field.
// you can add custom key value pairs to be used inside your callbacks.
function wporg_field_pill_cb( $args ) {
   // get the value of the setting we've registered with register_setting()
   $options = get_option( 'wporg_options' );
   // output the field
   ?>
    <select id=<?php echo esc_attr( $args[ 'label_for' ] ); ?>
            data-custom=<?php echo esc_attr( $args[ 'wporg_custom_data' ] ); ?>
            name=wporg_options[<?php echo esc_attr( $args[ 'label_for' ] ); ?>]
    >
        <option value=red <?php echo isset( $options[ $args[ 'label_for' ] ] ) ? ( selected( $options[ $args[ 'label_for' ] ], 'red', false ) ) : ( '' ); ?>>
         <?php esc_html_e( 'red pill', 'wporg' ); ?>
        </option>
        <option value=blue <?php echo isset( $options[ $args[ 'label_for' ] ] ) ? ( selected( $options[ $args[ 'label_for' ] ], 'blue', false ) ) : ( '' ); ?>>
         <?php esc_html_e( 'blue pill', 'wporg' ); ?>
        </option>
    </select>
    <p class=description>
      <?php esc_html_e( 'You take the blue pill and the story ends. You wake in your bed and you believe whatever you want to believe.', 'wporg' ); ?>
    </p>
    <p class=description>
      <?php esc_html_e( 'You take the red pill and you stay in Wonderland and I show you how deep the rabbit-hole goes.', 'wporg' ); ?>
    </p>
   <?php
}

/**
 * top level menu
 */
function wporg_options_page() {
   // add top level menu page
   add_menu_page(
      'WPOrg',
      'WPOrg Options',
      'manage_options',
      'wporg',
      'wporg_options_page_html'
   );
}

/**
 * register our wporg_options_page to the admin_menu action hook
 */
add_action( 'admin_menu', 'wporg_options_page' );

/**
 * top level menu:
 * callback functions
 */
function wporg_options_page_html() {
   // check user capabilities
   if ( ! current_user_can( 'manage_options' ) ) {
      return;
   }

   // add error/update messages

   // check if the user have submitted the settings
   // wordpress will add the settings-updated $_GET parameter to the url
   if ( isset( $_GET[ 'settings-updated' ] ) ) {
      // add settings saved message with the class of updated
      add_settings_error( 'wporg_messages', 'wporg_message', __( 'Settings Saved', 'wporg' ), 'updated' );
   }

   // show error/update messages
   settings_errors( 'wporg_messages' );
   ?>
    <div class=wrap>
        <h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
        <form action=options.php method=post>
         <?php
         // output security fields for the registered setting wporg
         settings_fields( 'wporg' );
         // output setting sections and their fields
         // (sections are registered for wporg, each field is registered to a specific section)
         do_settings_sections( 'wporg' );
         // output save settings button
         submit_button( 'Save Settings' );
         ?>
        </form>
    </div>
   <?php
}

我们提供 WordPress主题和插件定制开发服务

本站长期承接 WordPress主题、插件、基于 WooCommerce 的商店商城开发业务。 我们有 10 年WordPress开发经验,如果你想 用WordPress开发网站, 请联系微信: iwillhappy1314,或邮箱: amos@wpcio.com 咨询。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

*