Set selected images in the WordPress image uploader

I’m using wp.media to select images in a plugin. The only problem is I don’t know how to load the previously selected images.

uploader = wp.media.frames.file_frame = wp.media({
    title: 'Select images',
    button: {
        text: 'Select images'
    },
    multiple: true,
    selection: // current selection = images 173,174,175
});

Say someone previously selected 3 images, then they wish to add one more, this is what the frame should look like:

Read More

image selection

Related posts

Leave a Reply

1 comment

  1. I found an easy way to do it. It’s not perfect, but it’s simple.

    // $input is a hidden input with attachmend IDs, comma-separated
    var images = $input.val() || '-1';
    
    uploader = wp.media.gallery.edit('[gallery ids="' + images + '"]');
    
    uploader.state('gallery-edit').on('update', function(selection) {
      var images = [];
    
      selection.each(function(attachment) {
        images.push(attachment.toJSON().id);
      });
    
      $input.val(images.join(','));
    });
    
    uploader.open();