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');
as you can see in the picture, the value is 1 which is checked, but the checkbox never stays checked after refresh.
I prefer to use WordPress
checked()
function withprintf()
(see the page forsprintf()
for usage examples):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
Use the
checked
attribute of the checkbox tag instead: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.
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" : "";
whereis_checkbox_checked()
is the function that checks whether[jo_checkbox_del]
istrue
orfalse
.Your final code would look like this :