Options API 是 WordPress 1.0 引入的核心功能,用于创建、读取、更新和删除 WordPress 选项。它常与 Settings API 结合使用,以管理设置页面中定义的选项。
// 添加单个值选项
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.
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.
Options may be stored in the WordPress database in one of two ways: as a single value or as an array of values.
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');
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.
| 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() |