Open media frame and select an attachment

I’m using the following piece of code to open a media frame when clicking a link with a data-attachment_id attribute. This attribute holds the id of an attachment that I want to select when the frame opens:

jQuery(document).ready(function($){

    $( '#gallery_images_container' ).on( 'click', 'a.edit', function( event ) {
        var $el = $( this );
        var selected = $( this ).attr( 'data-attachment_id' );

        event.preventDefault();

        // If the media frame already exists, reopen it.
        if ( gallery_items_frame ) {

            // Select the attachment when the frame opens
            gallery_items_frame.on( 'open', function() {
                var selection = gallery_items_frame.state().get( 'selection' );
                if ( selected ) {
                    selection.add( wp.media.attachment( selected ) );
                }
            });

            // Open the modal.
            gallery_items_frame.open();

            return;
        }

        // Create the media frame.
        gallery_items_frame = wp.media.frames.gallery_items = wp.media({
            // Set the title of the modal.
            title: $el.data( 'choose' ),
            button: {
                text: $el.data( 'update' )
            },
            states: [
                new wp.media.controller.Library({
                    title: $el.data( 'choose' ),
                    filterable: 'all',
                    multiple: true
                })
            ]
        });

        // Select the attachment when the frame opens
        gallery_items_frame.on( 'open', function() {
            var selection = gallery_items_frame.state().get( 'selection' );
            if ( selected ) {
                selection.add( wp.media.attachment( selected ) );
            }
        });

        // Open the modal.
        gallery_items_frame.open();

    });

});

When I click the link for the first time, the frame opens and the pertinent attachment is selected. But, if I close the frame and click the link again, the frame opens again but no attachment is selected.

Any insights as to what I might be doing wrong?

Thanks in advance

1
1

Well, I found the answer myself. I hope it helps others:

I replaced both instances of:

if ( selected ) {
    selection.add( wp.media.attachment( selected ) );
}

with:

selection.reset( selected ? [ wp.media.attachment( selected ) ] : [] );

Apparently, the reset() function can be used to empty an array and then add elements to it, too.

Leave a Comment