Wordpress Widget Multiple Checkboxes with checked() Function

I have a widget where multiple checkboxes can be selected in the backend. Currently I have the following code in my form function of the widget.

<label for="<?php echo $this->get_field_id("types"); ?>">Types</label>
        <?php foreach ($types as $key => $val) : ?>
            <p>
                <input class="checkbox" id="<?php echo $this->get_field_id("types") . $key; ?>" name="<?php echo $this->get_field_name("types"); ?>[]" type="checkbox" value="<?php echo $key; ?>" <?php checked("1", array_key_exists($key, $instance["types"])); ?> />
                <label for="<?php echo $this->get_field_id("types") . $key; ?>"><?php echo $val; ?></label>
            </p>
        <?php endforeach; ?>

The values are saved correctly but checked values are not displayed in return. Can Someone help me with this. I'm not sure how checked() function should be used in this context

Thank You.

Upvotes: 1

Views: 1410

Answers (1)

SOLVED!!

In the given code I just need to set as follows,

<input class="checkbox" id="<?php echo $this->get_field_id("types") . $key; ?>" name="<?php echo $this->get_field_name("types"); ?>[]" type="checkbox" value="<?php echo $key; ?>" <?php checked(in_array($key, $instance["types"])); ?> />

instead of following

<input class="checkbox" id="<?php echo $this->get_field_id("types") . $key; ?>" name="<?php echo $this->get_field_name("types"); ?>[]" type="checkbox" value="<?php echo $key; ?>" <?php checked("1", array_key_exists($key, $instance["types"])); ?> />

Thanks @Mittul for helping !!

Upvotes: 1

Related Questions