Post navigation

Wordpress

Custom Widget Checkboxes Not Staying Checked

During the process of writing a few custom widgets for a custom WordPress theme I found a frustrating problem when using a checkbox as one of the widget options. The checkbox was functioning properly but when it was checked and then the widget options saved it was being unchecked.

The answer is really simple but I had a bit of trouble finding the solution – you have to make sure that the value saved is of the correct type, in this case a boolean as shown in the following code.


<input class="checkbox" type="checkbox" <?php checked( (bool) $instance['photo'], true ); ? > id="<?php echo $this->get_field_id( 'photo' ); ?>" name="<?php echo $this->get_field_name( 'photo' ); ? >" / >