Keep Check Mark in Checkbox

Posted by The Doctor on Dec 19, 2009 | Subscribe | Short Link
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.

Last modified by The Doctor on March 17, 2010

5 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>