WordPress 3.5 custom media upload for your theme options WordPress 3.5 custom media upload for your theme options wordpress wordpress

WordPress 3.5 custom media upload for your theme options


Your going about it in a way that was unintended. Your javascript code should probably look something like this:

$('.custom_media_upload').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();        $('.custom_media_image').attr('src', attachment.url);        $('.custom_media_url').val(attachment.url);        $('.custom_media_id').val(attachment.id);    })    .open();});


Don't forget to use wp_enqueue_media (new in 3.5) if you'r not on the post edit page

To use the old media upload box you can do this:

if(function_exists( 'wp_enqueue_media' )){    wp_enqueue_media();}else{    wp_enqueue_style('thickbox');    wp_enqueue_script('media-upload');    wp_enqueue_script('thickbox');}


I modified this code a bit more to make it usable for multiple fields at once:

HTML:

<!-- Image Thumbnail --><img class="custom_media_image" src="" style="max-width:100px; float:left; margin: 0px     10px 0px 0px; display:inline-block;" /><!-- Upload button and text field --><input class="custom_media_url" id="" type="text" name="" value="" style="margin-bottom:10px; clear:right;"><a href="#" class="button custom_media_upload">Upload</a>

jQuery:

jQuery(document).ready(function($){$('.custom_media_upload').click(function() {        var send_attachment_bkp = wp.media.editor.send.attachment;        var button = $(this);        wp.media.editor.send.attachment = function(props, attachment) {            $(button).prev().prev().attr('src', attachment.url);            $(button).prev().val(attachment.url);            wp.media.editor.send.attachment = send_attachment_bkp;        }        wp.media.editor.open(button);        return false;           });});