¿Cómo incluir un checkbox en el formulario backend del widget?
Estoy tratando de incluir un checkbox en el backend de mi widget. Pero no puedo obtener el valor (activado o desactivado) después de que el usuario lo envía. Pensé que el valor se almacenaría en "esc_attr( $check )" (como sucede cuando se usa un input de texto), pero no puedo recuperarlo.
Esto es lo que estoy intentando ahora:
public function form( $instance ) {
$check = isset( $instance[ 'check' ] ) ? $instance[ 'check' ] : 'off';
echo esc_attr( $check ); // Si el input es de tipo texto, muestra el valor
?>
<input class="widefat" id="<?php echo $this->get_field_id( 'check' ); ?>" name="<?php echo $this->get_field_name( 'check' ); ?>" type="checkbox" />
<?php
}
¿Cómo puedo hacer que esto funcione? ¿Y cómo obtengo el valor del checkbox en el frontend?
Primero, en la función widget:
function widget( $args, $instance ) {
extract( $args );
// Añade esta línea
$your_checkbox_var = $instance[ 'your_checkbox_var' ] ? 'true' : 'false';
// Cambia 'your_checkbox_var' por tu ID personalizado
// ...
}
En la función update:
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
// Añade esta línea
$instance[ 'your_checkbox_var' ] = $new_instance[ 'your_checkbox_var' ];
// Cambia 'your_checkbox_var' por tu ID personalizado
// ...
return $instance;
}
Finalmente, en la función form, añade esto:
<p>
<input class="checkbox" type="checkbox" <?php checked( $instance[ 'your_checkbox_var' ], 'on' ); ?> id="<?php echo $this->get_field_id( 'your_checkbox_var' ); ?>" name="<?php echo $this->get_field_name( 'your_checkbox_var' ); ?>" />
<label for="<?php echo $this->get_field_id( 'your_checkbox_var' ); ?>">Etiqueta de tu variable checkbox</label>
</p>
<!-- Recuerda cambiar 'your_checkbox_var' por tu ID personalizado también -->
EDITADO: Veamos el código completo de un widget 'Sobre Nosotros' usando un checkbox para mostrar/ocultar una imagen de avatar:
class about_us extends WP_Widget {
function about_us() {
$widget_ops = array( 'classname' => 'about_us', 'description' => __( 'Sobre Nosotros', 'wptheme' ) );
$this->WP_Widget( 'about_us', __( 'Sobre Nosotros', 'wptheme' ), $widget_ops, $control_ops );
}
function widget( $args, $instance ) {
extract( $args );
$title = apply_filters( 'widget_title', $instance[ 'title' ] );
$text = $instance[ 'text' ];
// La siguiente variable es para una opción tipo checkbox
$avatar = $instance[ 'avatar' ] ? 'true' : 'false';
echo $before_widget;
if ( $title ) {
echo $before_title . $title . $after_title;
}
// Recuperar el checkbox
if( 'on' == $instance[ 'avatar' ] ) : ?>
<div class="about-us-avatar">
<?php echo get_avatar( get_the_author_meta( 'user_email' ), '50', '' ); ?>
</div>
<?php endif; ?>
<div class="textwidget">
<p><?php echo esc_attr( $text ); ?></p>
</div>
<?php
echo $after_widget;
}
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance[ 'title' ] = strip_tags( $new_instance[ 'title' ] );
$instance[ 'text' ] = strip_tags( $new_instance[ 'text' ] );
// La actualización para la variable del checkbox
$instance[ 'avatar' ] = $new_instance[ 'avatar' ];
return $instance;
}
function form( $instance ) {
$defaults = array( 'title' => __( 'Sobre Nosotros', 'wptheme' ), 'avatar' => 'off' );
$instance = wp_parse_args( ( array ) $instance, $defaults ); ?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>">Título</label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $instance[ 'title' ] ); ?>" />
</p>
<!-- El checkbox -->
<p>
<input class="checkbox" type="checkbox" <?php checked( $instance[ 'avatar' ], 'on' ); ?> id="<?php echo $this->get_field_id( 'avatar' ); ?>" name="<?php echo $this->get_field_name( 'avatar' ); ?>" />
<label for="<?php echo $this->get_field_id( 'avatar' ); ?>">Mostrar avatar</label>
</p>
<p>
<label for="<?php echo $this->get_field_id( 'text' ); ?>">Sobre Nosotros</label>
<textarea class="widefat" id="<?php echo $this->get_field_id( 'text' ); ?>" rows="10" cols="10" name="<?php echo $this->get_field_name( 'text' ); ?>"><?php echo esc_attr( $instance[ 'text' ] ); ?></textarea>
</p>
<?php
}
}
register_widget( 'about_us' );
Probado y funcionando.
Edición (2015-Sept-08): ¡Importante! Ese ejemplo de widget usa constructores estilo PHP4, sin embargo WordPress 4.3 cambia a PHP5, por lo que deberías cambiar los constructores también. Más información aquí.
Si usas el plugin 'theme-check' verás un aviso sugiriendo que uses __construct()
en lugar de WP_Widget
. Elimina la primera función y añade la siguiente:
function __construct() {
parent::__construct(
'about_us', // ID Base
__( 'Sobre Nosotros', 'wptheme' ), // Nombre
array( 'description' => __( 'Sobre Nosotros', 'wptheme' ), ) // Argumentos
);
}

Sí, lo uso en un widget para activar/desactivar la imagen de avatar. Funciona muy bien para mí.

Ok. Creo que para mayor claridad deberías agregar en la respuesta la asignación por defecto para $instance['your_checkbox_var']
en la función form.

La asignación por defecto es 'avatar' en lugar de 'your_checkbox_var'. Escribí 'your_checkbox_var', en realidad, para hacerlo más claro. De cualquier modo voy a modificar mi respuesta con el ejemplo por defecto. Gracias por el consejo :)

@Gerard, intenta configurar el avatar activado por defecto y no podrás desactivarlo
