I’m trying to include a checkbox in my widget back end. But I cannot get the value (on or off) after the user submits it. I thought the value would be stored in “esc_attr( $check )” (as it is when using a text input), but I cannot retrieve it.
This is what I’m trying now:
public function form( $instance ) {
$check = isset( $instance[ 'check' ] ) ? $instance[ 'check' ] : 'off';
echo esc_attr( $check ); // If the input is type text it outputs the value
?>
<input class="widefat" id="<?php echo $this->get_field_id( 'check' ); ?>" name="<?php echo $this->get_field_name( 'check' ); ?>" type="checkbox" />
<?php
}
How can I get this to work? Also how do I get the value of the checkbox in the front end?
First, on function widget:
On function update:
Finally, on function form, add this:
EDIT:
Let’s see the full code of an ‘About Us’ widget using a checkbox to show/hide an avatar image:
Tested and working.
Edit (2015-Sept-08): Important! That widget example uses PHP4 style constructors, however WordPress 4.3 switches to PHP5, so you should switch the constructors, too. More information, here.
If you use the plugin ‘theme-check’ you will see a notice suggesting you to use
__construct()
instead ofWP_Widget
. Remove the first function and add the following one: