Modify the array of selected images in media modal

I’m creating a plugin which checks for duplicate media items on upload. If a file is uploaded, and it already exists in the media library, I’m presenting the user with the option to delete the uploaded file and insert the existing file instead.

In the modal media window (the one that appears when clicking “Add Media” above the post editor) I’ve got everything working to detect the duplicate file, and offer a checkbox the user can click to delete the duplicate (via ‘wp_ajax_save-attachment-compat’). After the user has deleted the new file, I need to find a way to modify the JavaScript array of currently selected media items, to replace the post ID of the deleted file with the post ID of the duplicate, so when the user clicks “Insert Into Post”, the correct image will get inserted.

Read More

Here’s the scratch code I’m currently using. This is firing whenever a new selection is made in the default media modal.

( function( $ ) {

    var _AttachmentDisplay = wp.media.view.Settings.AttachmentDisplay;
    wp.media.view.Settings.AttachmentDisplay = _AttachmentDisplay.extend({
        render: function() {
            _AttachmentDisplay.prototype.render.apply(this, arguments);
            selection = this.controller.state().get('selection').first().toJSON();
            //selection = this.controller.state().get('selection');

            filename = selection.filename;

            attachment = wp.media.attachment(id);  // get attachment with id

            console.dir(filename);
            console.dir(selection);
        }
    });

} )( jQuery );

Related posts

Leave a Reply

1 comment

  1. I’m able to do the following in media modal:

              var selection = wp.media.frame.state().get('selection'); // get selected collection
              attachment = wp.media.attachment(id);  // get attachment with id
              attachment.fetch();
              selection.add(attachment);  // add attachment to selection collection
    

    There should be .remove() method or something similar.