In this tutorial we will see how to open the WordPress media uploader and let user upload or select a single image. Once the image is selected, media uploader fires the callback with the selected image 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 image data once user selects the image.
function open_media_uploader_image()
{
media_uploader = wp.media({
frame: "post",
state: "insert",
multiple: false
});
media_uploader.on("insert", function(){
var json = media_uploader.state().get("selection").first().toJSON();
var image_url = json.url;
var image_caption = json.caption;
var image_title = json.title;
});
media_uploader.open();
}
You need to call the open_media_uploader_image()
JavaScript function to launch the media uploader and fire callback when selection is completed.