在WordPress中,update_option()
和 get_option()
是两个非常常用的函数,用于保存和检索设置。以下是如何使用这两个函数的步骤和示例:
update_option()
这个函数用于更新WordPress数据库中的选项值。
语法:
bool update_option( string $option, mixed $value, string|bool $autoload = 'yes' )
$option
: 选项名称(字符串),通常是一个独特的标识符。$value
: 要保存的值,可以是字符串、数组或任何其他类型。$autoload
: 是否在WordPress启动时自动加载此选项。默认为 'yes'。
示例:
update_option('my_custom_option', 'My custom value');
get_option()
这个函数用于从WordPress数据库中检索选项值。
语法:
mixed get_option( string $option, mixed $default = false )
$option
: 要检索的选项名称(字符串)。$default
: 如果选项不存在,则返回的默认值。
示例:
$my_value = get_option('my_custom_option', 'Default value if not set');
使用示例
假设你想要创建一个自定义设置页面,用户可以在其中输入一些信息,并保存到数据库中。以下是如何使用这两个函数的完整示例:
// 添加设置页面到WordPress管理菜单
function my_custom_settings_page() {
add_menu_page(
'My Custom Settings', // 页面标题
'My Settings', // 菜单标题
'manage_options', // 能访问页面的用户角色
'my-custom-settings', // 页面slug
'my_custom_settings_page_html' // 调用函数以输出页面内容
);
}
add_action('admin_menu', 'my_custom_settings_page');
// 输出设置页面HTML
function my_custom_settings_page_html() {
?>
<div class="wrap">
<h1>My Custom Settings</h1>
<form method="post" action="options.php">
<?php
settings_fields('my_custom_settings_group'); // 输出隐藏的表单字段
do_settings_sections('my-custom-settings'); // 输出设置部分和字段
?>
<table class="form-table">
<tr valign="top">
<th scope="row">Custom Text</th>
<td><input type="text" name="my_custom_option" value="<?php echo esc_attr(get_option('my_custom_option')); ?>" /></td>
</tr>
</table>
<?php submit_button(); ?>
</form>
</div>
<?php
}
// 注册设置
function my_custom_settings_register() {
register_setting(
'my_custom_settings_group', // 选项组名
'my_custom_option' // 选项名
);
}
add_action('admin_init', 'my_custom_settings_register');
在这个示例中,我们创建了一个自定义设置页面,用户可以在其中输入文本。使用 update_option()
函数将输入的值保存到数据库中,而 get_option()
函数用于在表单中显示当前保存的值。当用户提交表单时,WordPress会自动处理 update_option()
函数来更新选项值。