In this tutorial we will see how to open the WordPress media uploader and let user upload or select multiple images. Once the images are selected, media uploader fires the callback with the selected images information.
First you need make sure that Media Uploader is enqueued. Here is the code to enqueue media uploader
{
wp_enqueue_media();
}
add_action("admin_enqueue_scripts", "enqueue_media_uploader");
Now we can use the interfaces provided by media uploader library to open it. Here is the code on how to open it and get the images data once user selects the images.
function open_media_uploader_multiple_images()
{
media_uploader = wp.media({
frame: "post",
state: "insert",
multiple: true
});
media_uploader.on("insert", function(){
var length = media_uploader.state().get("selection").length;
var images = media_uploader.state().get("selection").models
for(var iii = 0; iii < length; iii++)
{
var image_url = images[iii].changed.url;
var image_caption = images[iii].changed.caption;
var image_title = images[iii].changed.title;
}
});
media_uploader.open();
}
You need to call the open_media_uploader_multiple_images()
JavaScript function to launch the media uploader and fire callback when selection is completed.
Leave a Reply