使用register_setting时修改checkbox的checked属性

开发 WordPress 插件时,有时会在后台提供基于 checkbox 的确认选项,使用官方提供的 register_setting 存值时,应该如何取值并更新 checked 属性呢?
正文
例子
这是一个简单的插件后台设置面板的例子:
<?php
function RegMenu(){
add_menu_page(
"页面标题",# 页面标题
"菜单标题",# 菜单标题
"administrator",# 谁能看到
"my-test-setting",# 设置页面别名(url访问)
"output_settingpage",# 输出函数
"dashicons-heart" #icon url
);
add_submenu_page( # 添加子菜单
"my-test-setting", # 父菜单别名
"页面标题", #页面标题
"子菜单标题", # 菜单标题
"administrator",
"my-test-setting1", # 页面别名
"output_settingpage1" # 输出函数
);
add_action('admin_init', 'reg_custom_settings');
}
fcunction reg_custom_settings(){
register_setting('test_group','zm_test_isopen');
}
function output_settingpage(){ ?>
<form method="post" action="options.php">
<?php settings_fields('test_group'); ?>
<input type="checkbox" name="zm_test_isopen" value="1" <?php checked( '1', get_option( 'zm_test_isopen' ),true ); ?>/>Test</label>
<?php submit_button(); ?>
</form>
<?php
}
function output_settingpage1(){
}
?>
其中, checked( '1', get_option( 'zm_anti_copy_open' ),true )
即为 WordPress 提供的设置元素 checked
属性的方法。
WordPress checked 详解
首先看一下 checked() 函数的定义:
//Outputs the html checked attribute.
checked(
mixed $checked, # One of the values to compare
mixed $current = true, # The other value to compare if not just true
bool $echo = true # Whether to echo or just return the string
)
下面这两种方法是等效的:
<input type='checkbox' name='zm_test_isopen' value='1'
<?php if ( 1 == $options['zm_test_isopen'] ) echo 'checked="checked"'; ?> />
<input type="checkbox" name="zm_test_isopen" value="1"
<?php checked("1",$options['zm_test_isopen'], 1 ); ?> />
Html form 表单提交时,如果没勾选 checkbox,则提交里就没有这子项,如果勾选了,提交的表单里会有对应 name 的子项,其值为value
值。
checked() 函数内会将 $checked 值与 $current 值比较,如果相同,则认为勾选了此项,输出 checked
。