【问题标题】:Wordpress settings page, how to default the state of a checkbox to checked?Wordpress设置页面,如何将复选框的状态默认为选中?
【发布时间】:2013-08-05 14:43:05
【问题描述】:

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

<?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('sold_text') 定义。

【问题讨论】:

  • 和函数get_option() ?
  • get_option() 呢?

标签: php wordpress checkbox


【解决方案1】:

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

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

所以我做了:add_option('sold_text') 的值为'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'); ?> />

【讨论】:

    【解决方案2】:

    复选框存储为 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

    【讨论】:

      猜你喜欢
      • 2019-05-10
      • 1970-01-01
      • 2014-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-19
      • 2021-12-28
      • 2015-11-17
      相关资源
      最近更新 更多