3

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.

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 );

1 Answer 1

3

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.

2
  • Can you give me a little more context for this code? I'm getting "id is not defined." I'll add my current scratch code so you can see what I'm working with.
    – bcorkins
    May 1, 2014 at 3:55
  • Figured it out, sorry for the dumb question. Thanks!
    – bcorkins
    May 1, 2014 at 4:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.