15

I'm trying to create an option in the WP modal media window to detect duplicate files and delete a newer file if an older duplicate is found. I have the following code working (in conjunction with the 'attachment_fields_to_edit' filter) to deselect a duplicate file and select the original file in the media modal. What I'd like to do is, when a user clicks the button, delete the original file (or at least hide it in the media library window so I can delete it later).

( function( $ ) {

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

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

                e.preventDefault();

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

                    currentattachment = wp.media.attachment(id);
                    selection.remove(currentattachment);

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

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

                }
            });
        }
    });

} )( jQuery );

The interface looks like the attached image.

screenshot of duplicate media check

I can see in media-views.js at line 5873 that there's a deleteAttachment function bound to 'click .delete-attachment'. How can I access this, given my current setup, by passing in an image ID or attachment object?

2
  • 4
    Is this question still open or have you found an answer yet?
    – engelen
    Jun 26, 2014 at 10:41
  • @engelen this question now have an open bounty. So go for it :-) Aug 6, 2014 at 10:29

2 Answers 2

5

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.

2
  • 1
    Thanks, looks good to me. Of course my JS skills and knowledge of those parts of WordPress isn't that great. Definitely want to try this next week. Another thing, lets pretend I don't know a lot about WP, how can I make use of the code you posted? Aug 8, 2014 at 21:22
  • As I haven't found the time to try either of your solutions I have given the bounty to the answer of @bonger - just because it seems completer, thanks again for answering though. Aug 13, 2014 at 10:15
5
+50

Attempting a somewhat canonical (or at least bountiful) answer, this is the javascript for wpse142997.js in the child template directory:

jQuery( document ).ready(function() {
    ( function( $ ) {
        var media = wp.media,
            l10n = media.view.l10n = typeof _wpMediaViewsL10n === 'undefined' ? {} : _wpMediaViewsL10n,
            attachments = media.model.Attachments.all,
            attachments_uploaded = [];

        if ( typeof wp.Uploaded === 'undefined') return;

        // Keep track of files uploaded.
        wp.Uploader.queue.on( 'add', function ( attachment ) {
            attachments_uploaded.push( attachment );
        });

        // The Uploader (in wp-includes/js/plupload/wp-plupload.js) resets the queue when all uploads are complete.
        wp.Uploader.queue.on( 'reset', function () {
            var idx, uploaded = attachments_uploaded.slice(0); // Clone
            attachments_uploaded = [];
            for ( idx = 0; idx < uploaded.length; idx++ ) {
                if ( uploaded[idx].get('name').match(/-[0-9]+$/) ) {
                    $.post( ajaxurl, {
                            action: 'wpse142997_is_dup',
                            dup_id: uploaded[idx].id,
                            nonce: wpse142997_params.is_dup_nonce
                        }, function( response ) {
                            var original, dup, dup_view, sidebar, selection;
                            if ( response && !response.error && response.original_id && response.dup_id ) {
                                original = attachments.get( response.original_id );
                                dup = attachments.get( response.dup_id );
                                if ( original && dup ) {
                                    dup.set( 'dup_original', original ); // May be ungood - mostly doing it so can use wp.templates.
                                    dup_view = media.view.Attachment.extend({
                                        tagName:   'div',
                                        className: 'attachment-dmc',
                                        template: media.template('attachment-dmc'),
                                        events: {
                                            'click button.dmc': 'removeDupSelectOriginal'
                                        },
                                        initialize: function() {
                                            this.focusManager = new media.view.FocusManager({
                                                el: this.el
                                            });
                                            media.view.Attachment.prototype.initialize.apply( this, arguments );
                                        },
                                        render: function() {
                                            if ( this.get_dup_original() ) {
                                                media.view.Attachment.prototype.render.apply( this, arguments );
                                                this.focusManager.focus();
                                            }
                                            return this;
                                        },
                                        removeDupSelectOriginal: function( event ) {
                                            var dup_original = this.get_dup_original();
                                            event.preventDefault();

                                            if ( dup_original && confirm( l10n.warnDelete ) ) {
                                                this.model.destroy();
                                                this.controller.state().get('selection').add( dup_original );
                                                this.remove();
                                            }
                                        },
                                        get_dup_original: function () {
                                            var dup_original = this.model.get('dup_original');
                                            return dup_original && attachments.get( dup_original.id ) ? dup_original : null;
                                        }
                                    });
                                    // A hacky way to get the sidebar.
                                    sidebar = media.frame.content.view.views.get('.media-frame-content')[0].sidebar;
                                    selection = sidebar.controller.state().get('selection');
                                    // The sidebar boxes get deleted and recreated on each select - hack into this to do the same.
                                    selection.on( 'selection:single', function ( event ) {
                                        if ( selection.single().get('dup_original') ) {
                                            sidebar.set( 'dmc', new dup_view({
                                                controller: sidebar.controller,
                                                model: selection.single(),
                                                priority: 100
                                            }) );
                                        }
                                    } );
                                    selection.on( 'selection:unsingle', function ( event ) {
                                        sidebar.unset('dmc');
                                    } );
                                    // Refire the select as we missed it (could/should just do the view create code here again).
                                    selection.trigger('selection:single');
                                }
                            }
                        }, 'json'
                    );
                }
            }
        });
    } )( jQuery );
});

This is the functions.php:

function wpse142997_wp_enqueue_scripts() {
    wp_enqueue_script( 'wpse142997', get_stylesheet_directory_uri() . '/wpse142997.js', array( 'jquery', 'media-views' ), '1.0' );
    $params = array(
        'is_dup_nonce' => wp_create_nonce( 'wpse142997_is_dup_submit_' ),
    );
    wp_localize_script( 'wpse142997', 'wpse142997_params', $params );
    ob_start();
    ?>
<style>
.attachment-dmc { float:left; overflow:hidden; position:relative; }
.attachment-dmc div { background-color:#FFEBE7; border:1px solid #CB9495; border-radius:5px; margin-top:16px; padding:6px; }
.attachment-dmc div h3 { margin-top:0; }
.attachment-dmc div h3 span { background-color:#E70000; border-radius:5px; color:white; margin-top:0; padding:0 6px; }
</style>
    <?php
    wp_add_inline_style( 'media-views', str_replace( array( '<style>', '</style>' ), '', ob_get_clean() ) );
}

function wpse142997_print_media_templates() {
?>
<script type="text/html" id="tmpl-attachment-dmc">
    <# if ( data.dup_original ) { #>
        <div>
            <h3><span><?php _e( 'Duplicate file detected' ); ?></span></h3>
            <p>
                <?php _e( 'This file appears to be a duplicate of <a href="{{ data.dup_original.attributes.editLink }}&amp;image-editor" target="_blank">{{ data.dup_original.attributes.filename }}</a> uploaded on {{ data.dup_original.attributes.dateFormatted }}' ); ?>
            </p>
            <button id="run_dmc" class="dmc" name="dmc"><?php _e( 'Remove duplicate and select original' ); ?></button>
        </div>
    <# } #>
</script>
<?php
}

function wpse142997_is_dup() {
    $ret = array( 'error' => false );

    if ( ! check_ajax_referer( 'wpse142997_is_dup_submit_', 'nonce', false /*die*/ ) ) {
        $ret['error'] = __( 'Permission error' );
    } else {
        $dup_id = isset( $_POST['dup_id'] ) ? $_POST['dup_id'] : '';
        if ( ! $dup_id || ! ( $post = get_post( $dup_id ) ) ) {
            $ret['error'] = __( 'Bad dup_id' );
        } else {
            $post_name = preg_replace( '/-[0-9]+$/', '', $post->post_name ); 
            global $wpdb;
            $sql = $wpdb->prepare( 'SELECT ID FROM ' . $wpdb->posts . ' WHERE'
                . ' post_title = %s AND post_type = %s AND post_mime_type = %s AND post_status = %s AND post_name = %s ORDER BY post_date ASC LIMIT 1',
                $post->post_title, $post->post_type, $post->post_mime_type, $post->post_status, $post_name
            );
            if ( $original_id = $wpdb->get_var( $sql ) ) {
                $ret['original_id'] = $original_id;
                $ret['dup_id'] = $dup_id;
            }
        }
    }

    wp_send_json( $ret );
}

add_action( 'admin_enqueue_scripts', 'wpse142997_wp_enqueue_scripts' );
add_action( 'print_media_templates', 'wpse142997_print_media_templates' );
add_action( 'wp_ajax_wpse142997_is_dup', 'wpse142997_is_dup' );

The javascript tries to follow the WP Media Modal way as much as I understand it, which is only partial. It creates a media.view.Attachment and uses a wp.template template. There're a few hacky bits - getting the sidebar in particular via a long reach into the frame object seems suspect (and was only found after a lot of poking around).

3
  • Thanks, this definitely is kind of what I was aiming for. About the canonical part, there aren't a lot of reasons to chose from and I couldn't figure out a better text on my own, so this is pretty near. I will take a closer look next week. Aug 8, 2014 at 21:27
  • I copied the code into the 2014 functions.php and set up the js as described and still can't see the duplicate notification section. What actions should I perform once the code is in place to see this?
    – KalenGi
    Aug 11, 2014 at 0:19
  • I assume you uploaded a duplicate image?!...
    – bonger
    Aug 11, 2014 at 5:07

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.