Starting in WordPress version 3.5, a new multimedia uploader is available to developers! Wohooo! This allows users to pick or upload an image file and then have that object data returned to your javascript for use any way you like.
Make sure to call wp_enqueue_media() from within the admin_enqueue_scripts action hook. This magically adds all dependencies to the page. Includes sugar, spice, and everything nice.
add_action('admin_enqueue_scripts', my_enqueue_scripts);
function my_enqueue_scripts() {
wp_enqueue_media();
}
You can bind the function to any action... but you probably want it to occur when the user clicks on a button:
<button class="custom_media_upload_button" />
If you want to use the returned value in a form, you may want some fields to store the data:
<input type="hidden" name="attachment_id" id="attachment_id" value="">
<input type="hidden" name="attachment_url" id="attachment_url" value="">
<img id="attachment_preview" src="" />
Bind the following function to your media upload button.
$('.custom_media_upload_button').click(function(e) {
e.preventDefault();
var custom_uploader = wp.media({
title: 'Custom Title',
button: {
text: 'Custom Button Text'
},
multiple: false // Set this to true to allow multiple files to be selected
})
.on('select', function() {
var attachment = custom_uploader.state().get('selection').first().toJSON();
// Do some fun things with this data when it is available!
console.log(attachment);
// Example of the magical things we could do...
$("#attachment_id").val(attachment.id);
$("#attachment_url").val(attachment.url);
$("#attachment_preview").attr('src', attachment.url);
})
.open();
});
http://mikejolley.com/2012/12/using-the-new-wordpress-3-5-media-uploader-in-plugins/ http://codestag.com/how-to-use-wordpress-3-5-media-uploader-in-theme-options/ http://stackoverflow.com/questions/13847714/wordpress-3-5-custom-media-upload-for-your-theme-options#answer-16070511