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 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 )
);
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']);} />";
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With