Delete an attachment in the WP media modal window

You just have to call destroy method on the attachment model. This will both remove the attachment from the Media Library view, and send an ajax call to the backend to delete the attachment in the database and all linked files in uploads directory.

You do not need to convert the attachment to JSON to get the id : you can directly manipulate the Backbone models. The selection is a collection of several attachments.

( function( $ ) {

    var _AttachmentDisplay = wp.media.view.Settings.AttachmentDisplay;
    wp.media.view.Settings.AttachmentDisplay = _AttachmentDisplay.extend({
        render: function() {
            _AttachmentDisplay.prototype.render.apply(this, arguments);

            $('button.dmc').on('click', $.proxy(function(e){

                e.preventDefault();
                selection = this.controller.state().get('selection');
                firstAttachment = selection.first();

                var id = $(e.currentTarget).data("id");
                if(currentselection.id == id) {

                    selection.remove(firstAttachment);
                    firstAttachment.destroy();

                    console.dir(wp.media.view.Attachment);

                    newattachment = wp.media.attachment($(e.currentTarget).data("original"));
                    selection.add(newattachment);

                }
            }, this));
        }
    });

} )( jQuery );

I have also added a $.proxy call to be able to use this inside the click event callback.

Leave a Comment