I am trying to implement a custom WP Media uploader within a plugin. I want multiple images to be uploaded also.
I have the following javascript to open the media uploader. The modal opens fine and I am able to select existsing media. I am also able to upload new media sucessfully, but when uploading the new media, it will not display within the media uploader. There is a thumbnail of the new image on the right hand side of the uploader but not thumbnail to select within the actual uploader.
jQuery( document ).ready(function( $ ){
var image_uploader;
$('#image-button').click(function(e){
e.preventDefault();
//If the uploader object has already been created, reopen the dialog
if (image_uploader) {
image_uploader.open();
return;
}
//Extend the wp.media object
image_uploader = wp.media.frames.file_frame = wp.media({
title: 'Choose Image',
button: {
text: 'Choose Image'
},
multiple: true,
library: {
type: [ 'image' ],
//filterable: 'all',
editable: false,
},
});
//When files are selected, extract information into JSON object
image_uploader.on('select', function() {
var attachments = image_uploader.state().get('selection').map(
function( attachment ) {
attachment.toJSON();
return attachment;
}
);
var i;
// Remove the existing images
$('.item-image').remove();
$('input[name="image_id_array[]"]').remove();
// Add the images to the display area
for (i = 0; i < attachments.length; ++i) {
$('#image-section').before(
'<img src="' + attachments[i].attributes.url + '" class="item-image" id="' + attachments[i].id + '">'
);
}
// Add the inputs for each image to the display area
for (i = 0; i < attachments.length; ++i) {
$('#image-section').before(
'<input type="hidden" name="image_id_array[]" id="image' + attachments[i].id + '" value="' + attachments[i].id + '">'
);
}
});
//Open the uploader dialog
image_uploader.open();
$('#remove-button').removeClass("hidden");
})
})
I have tried refactoring this code, but cannot work out why it is not allowing image display for newly uploaded images. I have tried on a cople of different machines and development sites, but the bug is the same on all of them.
Any help from you awesome guys would be much appreciated.