Keep Check Mark in Checkbox
Posted by The Doctor on Dec 19, 2009 | Subscribe | Short Link
in Tips
as checkbox, option panel, plugin, WordPress
in Tips
as checkbox, option panel, plugin, WordPress
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






[...] Can anyone help? Maybe after the fact, but I found this information useful in a few plugins … http://wpfirstaid.com/2009/12/keep-c…k-in-checkbox/ Edward Caissie aka Cais | Design by JellyBeen at BuyNowShop | Themes | [...]
Thanks!
This just helped me a lot for my List Category Posts plugin.
Strange that I haven’t found about the (bool) checking elsewhere. Regards!
@Fernando – Yes, it is strange that this was not common knowledge. I had to find other working plugins and sort out what was letting them work correctly to fix my own plugins. I posted it to help others with similar issues.