插件开发文档

设置保存API

💡 云策文档标注

概述

Options API 是 WordPress 1.0 引入的核心功能,用于创建、读取、更新和删除 WordPress 选项。它常与 Settings API 结合使用,以管理设置页面中定义的选项。

关键要点

  • 选项存储在 {$wpdb->prefix}_options 表中,前缀由 wp-config.php 中的 $table_prefix 定义。
  • 选项可以存储为单个值或数组值:单个值对应一个简单值,数组值可包含键值对,适合管理大量相关选项以提高性能。
  • 核心函数包括 add_option()、get_option()、update_option() 和 delete_option(),以及对应的多站点版本如 add_site_option()。

代码示例

// 添加单个值选项
add_option('wporg_custom_option', 'hello world!');
$option = get_option('wporg_custom_option');

// 添加数组值选项
$data_r = array('title' => 'hello world!', 1, false);
add_option('wporg_custom_option', $data_r);
$options_r = get_option('wporg_custom_option');
echo esc_html($options_r['title']);

注意事项

存储大量相关选项为数组可以减少数据库事务,提升性能,因为单个事务比多个独立事务更高效。


📄 原文内容

The Options API, added in WordPress 1.0, allows creating, reading, updating and deleting of WordPress options. In combination with the Settings API it allows controlling of options defined in settings pages.

Where Options are Stored?

Options are stored in the {$wpdb->prefix}_options table. $wpdb->prefix is defined by the $table_prefix variable set in the wp-config.php file.

How Options are Stored?

Options may be stored in the WordPress database in one of two ways: as a single value or as an array of values.

Single Value

When saved as a single value, the option name refers to a single value.

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

Array of Values

When saved as an array of values, the option name refers to an array, which itself may be comprised key/value pairs.

// array of options
$data_r = array('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']);

If you are working with a large number of related options, storing them as an array can have a positive impact on overall performance.

Accessing data as individual options may result in many individual database transactions, and as a rule, database transactions are expensive operations (in terms of time and server resources). When you store or retrieve an array of options, it happens in a single transaction, which is ideal.

Function Reference

Add Option Get Option Update Option Delete Option
add_option() get_option() update_option() delete_option()
add_site_option() get_site_option() update_site_option() delete_site_option()