I have a check box inside my admin page and the code looks like this (this code works and i can toggle my check box off and on and able to save changes)
add_settings_field(
'my_checkbox_default',
'Checkbox:',
'my_default_checkbox_settings_function',
'override_theme_display_options',
'override_theme_display_options'
);
function my_default_checkbox_settings_function(){
$options = get_option('override_theme_display_options');
if(isset($options['my_checkbox_default'])) {
$checked = 'checked';
} else {
$checked = '';
}
update_option('my_checkbox_default', $checked);
echo "<input type='checkbox' name='override_theme_display_options[my_checkbox_default']' ".$checked." id='my_checkbox_default' />";
}
Now I want to add default state “checked” to my check box.
So my check box setting function looks like this:
function my_default_checkbox_settings_function(){
$options = get_option('override_theme_display_options');
//Added default state "checked" to my check box
add_option('my_checkbox_default',$checked = 'checked');
if(isset($options['my_checkbox_default'])) {
$checked = 'checked';
} else {
$checked = '';
}
update_option('my_checkbox_default', $checked);
echo "<input type='checkbox' name='override_theme_display_options[my_checkbox_default']' ".$checked." id='my_checkbox_default' />";
}
My check box now has “checked” state as default , but now I can’t toggle my check box off and on anymore (it stays “checked” all the time no matter what I do), if I comment out my add_option()
obliviously my default “checked” state will not be set but I will be able to toggle and save my check box states again.
How can I add “checked” state by default and still be able to toggle and save options for my check box?
I will be more than happy to add 50 bounty for solving this. THX!
If this is a plugin, you need to set the option for the first time with
register_activation_hook
. If a theme, useafter_setup_theme
.There’s an alternative technique for
run_once
described in this WPSE Answer that works quite well too.Here’s a working example loosely based on yours and some Codex samples using
run_once
. Note the use of the functionchecked()
.