$('#media-button').click(function(e) {
e.preventDefault();
openMediaUploader();
});
function openMediaUploader() {
// If the uploader object has already been created, reopen the dialog
if ( mediaUploader ) {
mediaUploader.open();
return;
}
// Extend the wp.media object
mediaUploader = wp.media.frames.file_frame = wp.media({
title: 'Select image',
button: {
text: 'Select image'
},
library: {
type: [ 'image' ]
},
multiple: false
});
// When a file is selected, grab the URL and set it as the text field's value
mediaUploader.on('select', function() {
attachment = mediaUploader.state().get('selection').first().toJSON();
console.log(attachment.sizes);
$( '#js-cover-image-url' ).val( attachment.url );
$( '#js-cover-image-preview' ).attr( 'src', attachment.sizes.large.url );
});
// Open the uploader dialog
mediaUploader.open();
}