5

My checkbox field on a plugin page I wrote won't stay checked. The data is being saved, but the checkbox does not reflect the current stored value (checked).

Here is my function code:

public function jo_checkbox_del_setting()
{
    echo "<input id='jo_checkbox_del' name='jo_plugin_options[jo_checkbox_del]' type='checkbox' value='{$this->options['jo_checkbox_del']}' />";
}

and the add_settings_field code:

add_settings_field('jo_checkbox_del', 'Hide Delete Button: ', array($this, 'jo_checkbox_del_setting'), __FILE__, 'jo_main_section');

enter image description here

as you can see in the picture, the value is 1 which is checked, but the checkbox never stays checked after refresh.

4

4 回答 4

12

我更喜欢使用 WordPresschecked()功能(有关使用示例,请参阅页面) :printf() sprintf()

printf(
    '<input id="%1$s" name="jo_plugin_options[%1$s]" type="checkbox" %2$s />',
    'jo_checkbox_del',
    checked( isset( $this->options['jo_checkbox_del'] ), true, false )
);
于 2013-09-07T16:47:50.000 回答
3

如果设置了选项,则{checked($this->options['jo_checkbox_del']);}在元素内部使用以返回选中的属性。<input>

我还建议使用具有相同名称属性的隐藏输入来处理未选中该选项的情况

public function jo_checkbox_del_setting() {

        echo "<input type='hidden' name='jo_plugin_options[jo_checkbox_del]' value='0' />";

        echo "<input id='jo_checkbox_del' name='jo_plugin_options[jo_checkbox_del]' type='checkbox' value='{$this->options['jo_checkbox_del']}'  {checked($this->options['jo_checkbox_del']);} />";   
}
于 2013-09-07T16:36:57.443 回答
2

请改用checked复选框标签的属性:

public function jo_checkbox_del_setting()
{
    $checked = ( (int)$this->options['jo_checkbox_del'] == 1 ) ? 'checked' : '';
    echo "<input id='jo_checkbox_del' name='jo_plugin_options[jo_checkbox_del]' type='checkbox' value='{$this->options['jo_checkbox_del']}' $checked />";
}

这是预选复选框的唯一方法。将值设置为存储值不会自动触发它被设置。

另请注意,默认情况下,表单中的复选框根本不会被发送,除非它们被选中。

于 2013-09-07T16:29:50.103 回答
0

您需要验证复选框是否被选中并“告诉”页面的 HTML 部分。

所以,我建议你添加echo is_checkbox_checked() ? "checked" : "";where is_checkbox_checked()is 函数来检查[jo_checkbox_del]istruefalse.

您的最终代码将如下所示:

<?php
public function jo_checkbox_del_setting()
{ ?>
<input id='jo_checkbox_del' name='<?php echo jo_plugin_options[jo_checkbox_del]; ?>' type='checkbox' value='<?php echo {$this->options['jo_checkbox_del']}; ?>' <?php echo is_checkbox_checked() ? "checked" : ""; ?> />";
<?php } ?>
于 2013-09-07T16:32:22.520 回答