lundi 17 octobre 2016

How to autocheck checkbox in a metabox for gallery on uploading an image?

I'm creating a metabox that contains images uploaded to a post. I have added checkboxes to the images so as only the selected images are displayed in the frontend gallery. It has the ability to be checked/unchecked already.

Here's my code for checking or unchecking the checkboxes:

$checked = 'checked=checked'; //auto-checking images uploaded at the first time

$selected = (array) get_post_meta( $post->ID, 'gallery_image_check', true);
$selected = array_filter($selected);

if(!empty($selected) )
    $checked = in_array($attachment->ID,$selected) ? 'checked=checked' : '';

<input type="checkbox" <?php echo $checked ?> value="<?php echo $attachment->ID ?>"  name="gallery_image_check[]"  id="my_gallery_<?php echo $attachment->ID ?>" >

This works fine but, when I uncheck all images and update, all of the images get checked. This is possibly because $selected is empty. I have managed to fix it by using

if(isset($selected) )
    $checked = in_array($attachment->ID,$selected) ? 'checked=checked' : '';

which creates the problem I'm finding the solution for, i.e., newly uploaded images do not have a checked checkbox by default.

Please provide a solution with an explanation of what I might be missing. Thanks in advance!




Aucun commentaire:

Enregistrer un commentaire