WordPress Plugin Development Tutorial Manual - Setting Options

To make the admin interface easy to build, secure, and consistent in design with the WordPress admin interface, WordPress provides two core APIs.

set up

Setting up the API Focused on providing us with a way to create forms and manage form data.Options API focuses on providing us with a simple key/value system to manage data.

Quick Reference

See Using the Settings API and Options API Building customized settings pagesThe full example of the

Setting up the API

The Settings API added in WordPress 2.7 allows us to semi-automatically manage backend pages containing settings forms, letting us customize the settings pages, as well as the subsections and form fields within those pages. We can add new settings pages and form fields to them at the same time, or we can add settings subsections and form fields to existing pages.

Developers still need to manually register and validate form fields, but the Settings API avoids a lot of complex debugging for us to manage the underlying options.

When using the Settings API, the wp-admin/options.php page that receives form submissions undergoes a fairly strict permission check. The user has the manage_options capability to save data.

Why use the Settings API

Instead of using this API, we can develop our own settings page, which begs the question of what benefits the Settings API can bring us, here is a brief description of some of the benefits.

visual coherence

Using the API to generate interface elements ensures that our custom settings pages are consistent with the WordPress default admin interface, if we see a settings page that is styled 5 years ago, that page must not be using the settings API, if the settings API is used the custom page style will be updated along with the WordPress default style. So, one of the great benefits of using Settings API is that the design page looks like it should (with WordPress default style), thanks to the talented designers of WordPress, their work looks great.

Robustness (future-proofing)

Since the Settings API is part of the WordPress kernel, any updates will automatically update our Settings page, and if we create our own Settings page, WordPress kernel updates may break our customized settings. There will be more and more developers testing and maintaining these Settings API codes, so they will be more stable.

Easier work

Of course, the most immediate benefit is that the WordPress settings API does a lot of the work for us silently at the bottom, here are some examples:

  • Handling Form Submissions - Let WordPress process and store $_POST submissions
  • Includes security measures - allows us to get additional security measures such as random number verification
  • Clean data - can be automatically cleaned up for us as well as other parts of WordPress to make sure that submission strings are safe to use

function reference

Setting up registration / deregistrationAdding fields/subsections
register_setting()
unregister_setting()
add_settings_section()
add_settings_field()
Options form renderingerror message
settings_fields()
do_settings_sections()
do_settings_fields()
add_settings_error()
get_settings_errors()
settings_errors()

Using the Settings API

Add Settings

We can define a new setting using register_setting(), which inserts a record into the {$wpdb->prefix}_options data table. You can use add_settings_section() to add a new subsection to an existing settings page. New fields can be added on top of existing subsections using add_settings_field().

The register_setting() and the add_settings_*() functions mentioned should be added to admin_init.

Add Settings

register_setting(
   string $option_group,
    string $option_name, callable $sanitize_callback = '''
    callable $sanitize_callback = ''
);

See the function reference for register_setting() for a full description of the parameters.

Adding subsections

add_settings_section(
   string $id,
    
    callable $callback, string $page_section(
    string $page
);

Subsections are groups of settings with shared titles that we see on WordPress settings pages. In the plugin, we can add new subsections to an existing settings page instead of creating a new page. This lays our plugin easier to maintain and reduces the learning and usage costs for users.

See the function reference for add_settings_section() for a full description of the parameters.

typical example

<?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="NO NUMERIC NOISE KEY" 1000>
   <?php
}

Getting Settings

get_option(
   string $option, mixed $default = false
    mixed $default = false
);

utilization get_option() function to get the setting data, the function accepts two parameters: the name of the option and an optional default value for the option.

typical example

// Get the value of the option we registered with register_setting() above
$setting = get_option('wporg_setting_name');

Options API

The Options API introduced in WordPress 1.0 allows us to add, fetch, update, and delete WordPress options, and in conjunction with the Settings API, we can control customized options on the Settings page.

Where are the options saved?

The options are stored in the {$wpdb->prefix}_options In the data table.$wpdb->prefix leave it (to sb) wp-config.php configuration file in the $table_prefix Variable Definition.

How do I store options?

Options can be stored in the WordPress database as a single value or as an array.

single value

When saved as a single value, the option value is a single string, integer, etc.

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

arrays

When saved as an array, the option values are an array.

'hello world!]
// add a new option
add_option('wporg_custom_option', $data_r); // get an option.
// get an option
$options_r = get_option('wporg_custom_option'); // output the title.
// output the title
echo esc_html($options_r['title']); }

If we need to save a large number of options, saving them as an array may be helpful for performance improvement.

When we access many option data individually, it may result in many separate database transactions, which are usually expensive operations (in terms of time and server resources) whereas storing and fetching many options as an array generates only one database transaction, which is a more desirable operation.

function reference

Add OptionsGetting OptionsUpdate OptionsDelete Options
add_option()get_option()update_option()delete_option()
add_site_option()get_site_option()update_site_option()delete_site_option()

Customizing the settings page

Creating a custom settings page requires the Creating administrative menus(math.) genusUsing the Settings API respond in singingOptions API The relevant knowledge in the

Please read these sections before attempting to create a custom settings page.

The following example will help us quickly understand how to create a custom settings page.

Full example of creating a customized settings page

Here is a complete example of creating a custom settings page, in the following code we have added a top level menu called WPOrg, registered an option called wporg_options, and performed a CRUD add, check, change, delete operation using the Settings API and the Options API (including displaying an error/update message)

<?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="NO NUMERIC NOISE KEY" 1014><?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="NO NUMERIC NOISE KEY" 1011
 data-custom="NO NUMERIC NOISE KEY" 1010
 name="wporg_options[NO NUMERIC NOISE KEY" 1009]
>
        <option value="red" no numeric noise key 1008>
         <?php esc_html_e( 'red pill', 'wporg' ); ?>
        </option>
        <option value="blue" no numeric noise key 1006>
         <?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="/en/options.php/" method="post" data-trp-original-action="options.php">
         <?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' );
         ?>
        <input type="hidden" name="trp-form-language" value="en"/></form>
    </div>
   <?php
}

We offer WordPress Themes and Plugins Custom Development Services

This site has long undertaken WordPress themes, plugins, WooCommerce-based store mall development business. We have 10 years of experience in WordPress development, if you want to Developing Websites with WordPress, please contact WeChat: iwillhappy1314 or email: amos@wpcio.com for inquiries.

发表回复

Your email address will not be published. 必填项已用 * 标注

*