Wordpress设置页面,如何默认选中复选框的状态


Wordpress settings page, how to default the state of a checkbox to checked?

我有一个复选框,其默认状态为未选中:

<?php
function edit_theme_settings() {
    if ( get_option('sold_text') == true ) { $display = 'checked'; }
    else { $display = ''; }
    update_option( 'sold_text', $display );
?>
<input type="checkbox" name="sold_text" id="sold_text" <?php echo get_option('sold_text'); ?> />

我希望它的默认状态为未检查第一次显示表单时,它的"已检查"状态应该由get_option("old_text")定义。

在这种情况下,这两个建议都不适用,但我想我自己已经通过使用add_option()解决了它

将命名选项/值对添加到选项数据库表的安全方法如果该选项已经存在,它将不执行任何操作

所以我做了:add_option('sold_text')的值为"checked",因此复选框默认为checked。现在,由于选项已经存在,add_option()在下次加载或提交表单时不起任何作用,update_option(()处理复选框状态的更新。。。

<?php
function edit_theme_settings() {
add_option( 'sold_text', 'checked' );
if ( get_option('sold_text') == true ) { $display = 'checked'; }
else { $display = ''; }
update_option( 'sold_text', $display );
?>
<input type="checkbox" name="sold_text" id="sold_text" <?php echo get_option('sold_text'); ?> />

复选框存储为0或1(对于未选中、已选中),因此您需要这样的东西:

<input type="checkbox" name='sold_text' id='sold_text' value="1" <?= checked( get_option('sold_text'), 1, false );?> />

WP的checked()函数是为此而设计的:http://codex.wordpress.org/Function_Reference/checked