Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

image selection

like image 846
Oscar Broman Avatar asked Dec 05 '25 03:12

Oscar Broman


1 Answers

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();
like image 73
Oscar Broman Avatar answered Dec 07 '25 17:12

Oscar Broman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!