Adding Multiple Image Selection to WordPress Plug-Ins


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:
 * @License: GPL3

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

    var myplugin_media_upload;

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


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



        // Extend the object
        myplugin_media_upload = ={

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


         *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 ) {

                    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
                    '<div class="myplugin-image-preview"><img src="' + 
                    attachments[i].attributes.url + '" ></div>'

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




Commenter Ignore Button by CK's Plug-Ins

Leave a Reply

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