Show selected images on top in Media Manager

After reading up on the Backbone.js documentation I found out it’s quite easy to manually add attachments by ID to the library of the media frame.

You can just assign a reference to the library on the open event. Then create an instance of wp.media.attachment. Fetch it. And then call the add function on your library reference and passing the attachment with it. I had my attachment id’s in an array and looped through them like so:

file_frame.on('open',function(){

        var lib = file_frame.state().get('library');
        for (var i=0;i<ids.length;i++){
            var attachment = wp.media.attachment(ids[i]);
            attachment.fetch();
            lib.add(attachment);
        }
});

EDIT: Additionally I encountered a problem where the sorting got messed up sometimes and some of my attachments weren’t being placed on top of the list. So to make sure that they did I overrode the comparator function of the library like this to force compare on ID . It used to do get(key), but I turned it into get(‘id’):

lib.comparator = function ( a, b, options ) {
                var key   = this.props.get('orderby'),
                order = this.props.get('order') || 'DESC',
                ac    = a.cid,
                bc    = b.cid;

            a = a.get( 'id' );
            b = b.get( 'id' );

            if ( 'date' === key || 'modified' === key ) {
                a = a || new Date();
                b = b || new Date();
            }

            // If `options.ties` is set, don't enforce the `cid` tiebreaker.
            if ( options && options.ties )
                ac = bc = null;

            return ( 'DESC' === order ) ? compare( a, b, ac, bc ) : compare( b, a, bc, ac );
        } 

However it’s going to whine about the compare function being undefined. So I just declared it myself the same it is as in wp.media:

compare = function( a, b, ac, bc ) {
        if ( _.isEqual( a, b ) )
            return ac === bc ? 0 : (ac > bc ? -1 : 1);
        else
            return a > b ? -1 : 1;
    };

This comparator needs to be set before adding new attachments to the library. Because otherwise the problem will persist.

techhipbettruvabetnorabahisbahis forumutaraftarium24edusedueduedueduseduseduedueduedu