Question

I am developing a custom theme. I added a checkbox with the settings api. They all work except for the ones that are checked by default (checked="checked"). They do not save when they get unchecked (state only, value does save).

Now, there are two things I'd like to be able to do: 1 - save the checkbox state when unchecked on default checked checkboxes. 2 - save default checked checkboxes automatically without the user first having to click "Save changes". (so on page load save default checked checkboxes for example).

I searched everywhere for an answer already but I could not find anyone with this same question. They all handle checkboxes but none handle default "checked" checkboxes.

The code for the checkboxes:

echo '<input type="checkbox" class="theme-custom-checkbox" name="theme_custom_option" value="1" checked="checked"' . checked( 1, get_option( 'theme_custom_option' ), false ) . ' />';
Was it helpful?

Solution

With the code that you've added to your question, you're adding the HTML 'checked' attribute twice, which is probably why things are getting confused. You have it hard-coded as checked="checked", but then checked( 1, get_option( 'theme_custom_option' ), false ) will write another checked attribute corresponding to the actual value of the option.

You should be able to verify this would have been able to debug it by looking at the generated HTML with view-source or developer tools.

Taken from the docs page for the checked function in Wordpress https://developer.wordpress.org/reference/functions/checked/ your code should probably look something like this:

echo '<input type="checkbox" class="theme-custom-checkbox" name="theme_custom_option"  value="1" ' ;
echo checked( 1, get_option( 'theme_custom_option' ), false );
echo ' />';

Note code tidied a bit for readability

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top