• I’m trying to create a widget that enables user to select which categories will be displayed. The following is piece of codes I created but the changes of the checkbox state can’t be saved. There are only two values : the title and list of selected categories.

    function form($instance) {
        $instance = (array)$instance;
        if( empty($instance['title']) ) $instance['title'] = 'Category';
        $selected_categories = (array)$instance['category'];
        var_dump($selected_categories);
        ....
        $categories = get_categories( array('exclude'=> 1) );
        foreach($categories as $category) : ?>
        <div>
            <input type="checkbox" name="<?php echo $this->get_field_name('category'); ?>"
                value="<?php echo $category->cat_ID; ?>"
                <?php echo $category->cat_name; ?>
        </div>
        <?php endforeach; ?>
    }
    
    function update($new_instance, $old_instance) {
        $instance = $old_instance;
        $instance['title'] = strip_tags($new_instance['title']);
        $instance['category'] = $instance_new['category'];
    
        return $instance;
    }

    I observe the changes through var_dump($selected_categories). The value is always array(size=0) ignoring how many checkbox I checked.

    I have no idea how to passing array in $instance variable.

    Thanks in advance.

  • The topic ‘Checkbox array in WordPress widget?’ is closed to new replies.