Adding wp.media Multiple Image Selection to WordPress Plug-Ins

adding-multiple-images

Took a little while, but I finally figured out how to add WordPress Media Library multiple image selection for a process partly depicted above, part of a plug-in still in development.

My code follows. As I mentioned at StackExchange WordPress Development – where I first put the issue in the form of a question, at a point when I was unsure of my ability to answer it – I’d be happy to accept and credit improvements on this work from some true jQuery/WordPress expert, though the code seems to be working quite well so far.

/**
 * @Script: WordPress Multiple Image Selection in jQuery
 * @Version: 0.1
 * @Author: CK MacLeod
 * @Author URI: https://ckmacleod.com
 * @License: GPL3
 */

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

    var myplugin_media_upload;

    $('#myplugin-change-image').click(function(e) {

        e.preventDefault();

        // If the uploader object has already been created, reopen the dialog
        if( myplugin_media_upload ) {

            myplugin_media_upload.open();
            return;

        }

        // Extend the wp.media object
        myplugin_media_upload = wp.media.frames.file_frame = wp.media({

            //button_text set by wp_localize_script()
            title: button_text.title,
            button: { text: button_text.button },
            multiple: true //allowing for multiple image selection

        });

        /**
         *THE KEY BUSINESS
         *When multiple images are selected, get the multiple attachment objects
         *and convert them into a usable array of attachments
         */
        myplugin_media_upload.on( 'select', function(){

            var attachments = myplugin_media_upload.state().get('selection').map( 

                function( attachment ) {

                    attachment.toJSON();
                    return attachment;

            });

            //loop through the array and do things with each attachment

            var i;

            for (i = 0; i < attachments.length; ++i) {

                //sample function 1: add image preview
                $('#myplugin-placeholder').after(
                    '<div class="myplugin-image-preview"><img src="' + 
                    attachments[i].attributes.url + '" ></div>'
                    );

                //sample function 2: add hidden input for each image
                $('#myplugin-placeholder').after(
                    '<input id="myplugin-image-input' +
                    attachments[i].id '" type="hidden" 
                    name="myplugin_attachment_id_array[]"  value="' + 
                    attachments[i].id + '">'
                    );

             }

        });

    myplugin_media_upload.open();

    });

});
Commenter Ignore Button by CK's Plug-Ins

Leave a Reply

Your email address will not be published. Required fields are marked *

*