在WordPress中,update_option()
和 get_option()
是两个非常常用的函数,用于存储和检索插件或主题的设置。以下是如何使用这两个函数的基本步骤:
存储设置:使用 update_option()
update_option()
函数用于在WordPress数据库中创建或更新一个选项。
函数原型:
bool update_option( string $option, mixed $value, string $autoload = 'yes' )
$option
:选项名称(通常是一个字符串,推荐使用插件或主题的名称作为前缀以避免冲突)。$value
:要存储的值(可以是字符串、数组、整数等)。$autoload
:是否在WordPress启动时自动加载此选项。默认为 'yes'。
示例代码,存储一个名为 my_plugin_settings
的插件设置:
// 假设这是我们要存储的设置数组
$settings = array(
'setting1' => 'value1',
'setting2' => 'value2',
// 更多设置...
);
// 使用 update_option() 函数来存储设置
update_option('my_plugin_settings', $settings);
检索设置:使用 get_option()
get_option()
函数用于从WordPress数据库中检索一个选项的值。
函数原型:
mixed get_option( string $option, mixed $default = false )
$option
:要检索的选项名称。$default
:如果选项不存在,则返回的默认值。
示例代码,检索名为 my_plugin_settings
的插件设置:
// 使用 get_option() 函数来检索设置
$settings = get_option('my_plugin_settings', array());
// 现在 $settings 包含了存储的设置,如果没有设置,它将是一个空数组
完整示例
以下是一个完整的示例,展示了如何在插件中使用 update_option()
和 get_option()
来存储和检索设置:
// 当插件被激活时,确保有一个默认设置
function my_plugin_activate() {
$default_settings = array(
'setting1' => 'default_value1',
'setting2' => 'default_value2',
);
add_option('my_plugin_settings', $default_settings);
}
register_activation_hook(__FILE__, 'my_plugin_activate');
// 添加一个设置页面
function my_plugin_add_settings_page() {
add_options_page('My Plugin Settings', 'My Plugin', 'manage_options', 'my-plugin-settings', 'my_plugin_settings_page');
}
add_action('admin_menu', 'my_plugin_add_settings_page');
// 输出设置页面
function my_plugin_settings_page() {
?>
<div class="wrap">
<h1>My Plugin Settings</h1>
<form method="post" action="options.php">
<?php
settings_fields('my_plugin_settings_group');
do_settings_sections('my-plugin-settings');
?>
<table class="form-table">
<tr valign="top">
<th scope="row">Setting 1</th>
<td><input type="text" name="my_plugin_settings[setting1]" value="<?php echo esc_attr(get_option('my_plugin_settings')['setting1']); ?>" /></td>
</tr>
<tr valign="top">
<th scope="row">Setting 2</th>
<td><input type="text" name="my_plugin_settings[setting2]" value="<?php echo esc_attr(get_option('my_plugin_settings')['setting2']); ?>" /></td>
</tr>
</table>
<?php submit_button(); ?>
</form>
</div>
<?php
}
// 注册设置
function my_plugin_register_settings() {
register_setting('my_plugin_settings_group', 'my_plugin_settings');
}
add_action('admin_init', 'my_plugin_register_settings');
在这个示例中,我们添加了一个设置页面,用户可以在其中输入设置,这些设置将被存储在WordPress数据库中。我们还注册了一个设置组,这样WordPress就知道如何处理表单提交的数据。