Come includere una checkbox nel form backend del widget?

30 ago 2013, 17:40:35
Visualizzazioni: 23.2K
Voti: 21

Sto cercando di includere una checkbox nel backend del mio widget. Ma non riesco a ottenere il valore (on o off) dopo che l'utente lo invia. Pensavo che il valore sarebbe stato memorizzato in "esc_attr( $check )" (come avviene quando si usa un input di testo), ma non riesco a recuperarlo.

Questo è quello che sto provando ora:

public function form( $instance ) {
    $check = isset( $instance[ 'check' ] ) ? $instance[ 'check' ] : 'off';
    echo esc_attr( $check ); // Se l'input è di tipo testo, visualizza il valore
    ?>
    <input class="widefat" id="<?php echo $this->get_field_id( 'check' ); ?>" name="<?php echo $this->get_field_name( 'check' ); ?>" type="checkbox" />
    <?php 
}

Come posso farlo funzionare? Inoltre, come posso ottenere il valore della checkbox nel frontend?

0
Tutte le risposte alla domanda 1
5
25

Prima, nella funzione widget:

function widget( $args, $instance ) {
    extract( $args );
    // Aggiungi questa linea
    $your_checkbox_var = $instance[ 'your_checkbox_var' ] ? 'true' : 'false';
    // Sostituisci 'your_checkbox_var' con il tuo ID personalizzato
    // ...
}

Nella funzione update:

function update( $new_instance, $old_instance ) {
    $instance = $old_instance;
    // Aggiungi questa linea
    $instance[ 'your_checkbox_var' ] = $new_instance[ 'your_checkbox_var' ];
    // Sostituisci 'your_checkbox_var' con il tuo ID personalizzato
    // ...
    return $instance;
}

Infine, nella funzione form, aggiungi questo:

<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' ); ?>">Etichetta della tua variabile checkbox</label>
</p>
<!-- Ricorda di cambiare 'your_checkbox_var' con il tuo ID personalizzato -->

MODIFICA: Vediamo il codice completo di un widget 'Chi Siamo' che utilizza una checkbox per mostrare/nascondere un'immagine avatar:

class about_us extends WP_Widget {

function about_us() {
    $widget_ops = array( 'classname' => 'about_us', 'description' => __( 'Chi Siamo', 'wptheme' ) );
    $this->WP_Widget( 'about_us', __( 'Chi Siamo', 'wptheme' ), $widget_ops, $control_ops );
}

function widget( $args, $instance ) {
    extract( $args );
    $title = apply_filters( 'widget_title', $instance[ 'title' ] );
    $text = $instance[ 'text' ];
    // La seguente variabile è per un'opzione di tipo checkbox
    $avatar = $instance[ 'avatar' ] ? 'true' : 'false';

    echo $before_widget;

        if ( $title ) {
            echo $before_title . $title . $after_title;
        }

        // Recupera la 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' ] );
    // L'aggiornamento per la variabile della checkbox
    $instance[ 'avatar' ] = $new_instance[ 'avatar' ];
    return $instance;
}

function form( $instance ) {
    $defaults = array( 'title' => __( 'Chi Siamo', 'wptheme' ), 'avatar' => 'off' );
    $instance = wp_parse_args( ( array ) $instance, $defaults ); ?>
    <p>
        <label for="<?php echo $this->get_field_id( 'title' ); ?>">Titolo</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>
    <!-- La 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' ); ?>">Mostra avatar</label>
    </p>
    <p>
        <label for="<?php echo $this->get_field_id( 'text' ); ?>">Chi Siamo</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' );

Testato e funzionante.

Modifica (2015-Sett-08): Importante! Questo esempio di widget utilizza costruttori in stile PHP4, tuttavia WordPress 4.3 passa a PHP5, quindi dovresti modificare anche i costruttori. Maggiori informazioni qui.

Se utilizzi il plugin 'theme-check' vedrai un avviso che ti suggerisce di usare __construct() invece di WP_Widget. Rimuovi la prima funzione e aggiungi la seguente:

function __construct() {
    parent::__construct(
        'about_us', // ID Base
        __( 'Chi Siamo', 'wptheme' ), // Nome
        array( 'description' => __( 'Chi Siamo', 'wptheme' ), ) // Argomenti
    );
}
2 set 2013 16:29:27
Commenti

Sì, lo uso su un widget per abilitare/disabilitare l'immagine dell'avatar. Funziona molto bene per me.

Unix Unix
2 set 2013 19:25:39

Ok. Penso che per maggiore chiarezza dovresti aggiungere nella risposta l'assegnazione predefinita per $instance['your_checkbox_var'] nella funzione form.

gmazzap gmazzap
2 set 2013 19:55:27

L'assegnazione predefinita è 'avatar' invece di 'your_checkbox_var'. Ho scritto 'your_checkbox_var', in realtà, per renderlo più chiaro. Comunque modificherò la mia risposta con l'esempio predefinito. Grazie per il consiglio :)

Unix Unix
2 set 2013 20:20:52

@Gerard, prova a impostare l'avatar attivo di default e non sarai in grado di disattivarlo

Benn Benn
6 mar 2017 17:19:46

Questo ha funzionato per me quando ho usato 'on' e 'off' invece di TRUE e FALSE nella funzione. Ho anche usato un semplice controllo per l'istruzione if.. if ('on' = $myinstance) { ...mio codice... }

DJ_Davey DJ_Davey
6 apr 2019 21:40:57