First page of the checkbox archive.

Keep Check Mark in Checkbox

Posted by The Doctor on Dec 19, 2009 with 3 Comments | Short Link
Last modified by The Doctor on March 17, 2010
in Tips
as , , ,

Something I have come across recently in several plugins (mine included) was the checkbox in the option panel not staying checked!

The option itself was being maintained; the plugins are working according to expectations; but, the visual check mark in the box was not there. This can be become frustrating and annoying. A fix was needed. Here is it, in the form of a generic snippet:

<p>
	<input class="checkbox" type="checkbox" <?php checked( (bool) $instance['do_something'], true ); ?> id="<?php echo $this->get_field_id( 'do_something' ); ?>" name="<?php echo $this->get_field_name( 'do_something' ); ?>" />
	<label for="<?php echo $this->get_field_id( 'do_something' ); ?>"><?php _e('Display the Do Something action?'); ?></label>
</p>

The key is the (bool) in the checked() function. If it does not exist the checkbox will not maintain the visual check mark correctly.