Checkbox won’t stay checked on plugin settings page

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:

Read More
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.

Related posts

Leave a Reply

4 comments

  1. I prefer to use WordPress checked() function with printf() (see the page for sprintf() for usage examples):

    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 )
    );
    
  2. use {checked($this->options['jo_checkbox_del']);} inside the <input> element to return checked attribute if the option is set.

    I would also recommend on using a hidden input with the same name attribute to handle the case when the option is not checked

    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']);} />";   
    }
    
  3. Use the checked attribute of the checkbox tag instead:

    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 />";
    }
    

    This is the only way to have a pre-selected checkbox. Setting the value to the stored value will not automatically trigger it to be set.

    Also be aware that by default checkboxes in a form will not be sent along at all unless they are checked.

  4. You need to verify that checkbox is checked and “tell” the HTML part of the page about that.

    So, I suggest that you add echo is_checkbox_checked() ? "checked" : ""; where is_checkbox_checked() is the function that checks whether [jo_checkbox_del] is true or false.

    Your final code would look like this :

    <?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 } ?>