In this tutorial we will see how to open the WordPress media uploader and let user upload or select a image gallery. Once a gallery is selected, media uploader fires the callback with the selected gallery 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 gallery information once user selects a gallery
function open_media_uploader_gallery()
{
media_uploader = wp.media({
frame: "post",
state: "gallery-edit",
multiple: true
});
media_uploader.on("update", function(){
var length = media_uploader.state().attributes.library.length;
var images = media_uploader.state().attributes.library.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;
var image_description = images[iii].changed.description;
//this object contains URL for medium, small, large and full sizes URL.
var sizes = images[iii].changed.sizes;
}
});
media_uploader.open();
}
You need to call the open_media_uploader_gallery()
JavaScript function to launch the media uploader and fire callback when selection is completed.