List of checkboxes not saving in WordPress widget

Viewed 20

I try to get the names of the pages in a loop. In the widget, the page titles are displayed correctly, but the values are not saved.

How I can save the checked inputs?

Below Full Widget Code:

class Foo_Widget extends WP_Widget {

    /** Register widget with WordPress.*/
    function __construct() {
        parent::__construct(
            'foo_widget', // Base ID
            esc_html__( 'Widget Title', 'text_domain' ), // Name
            array( 'description' => esc_html__( 'A Foo Widget', 'text_domain' ), ) // Args
        );
    }

    /*** Front-end display of widget.*/
    public function widget( $args, $instance ) {
        echo $args['before_widget'];
        if ( ! empty( $instance['title'] ) ) {
            echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ) . $args['after_title'];
        }
        echo esc_html__( 'Hello, World!', 'text_domain' );
        echo $args['after_widget'];
    }

    /*** Back-end widget form.*/
    public function form( $instance ) {
    $mypages = get_pages( array( 
        'sort_column' => 'post_date', 
        'sort_order'  => 'desc' 
    ) );

    foreach( $mypages as $page ) {       
        $title = $page->post_title;
        $slug   = $page->post_name; 
    ?>
        <p>
            <label>
                <input type='checkbox' name='the_pages' id='<?php echo $slug ?>' value='<?php echo esc_attr( $title ); ?>'><?php echo esc_attr( $title ); ?>
            </label>
        </p>

    <? } ?>
    <?php }

    /*** Sanitize widget form values as they are saved.*/
    public function update( $new_instance, $old_instance ) {
        $instance = array();
        $instance['title'] = $new_instance[ 'title' ];

        return $instance;
    }
}


// register Foo_Widget widget
function register_foo_widget() {
    register_widget( 'Foo_Widget' );
}
add_action( 'widgets_init', 'register_foo_widget' );
?>

How should update() function looks like ?

0 Answers
Related