Skip to content

Instantly share code, notes, and snippets.

@manmar
Created June 23, 2015 08:35
Show Gist options
  • Save manmar/15994f5feed0be67a4f7 to your computer and use it in GitHub Desktop.
Save manmar/15994f5feed0be67a4f7 to your computer and use it in GitHub Desktop.
Use WordPress media uploader from custom meta fields or widgets
jQuery(document).ready(function($) {
var imageFrame;
$(document).on("click", ".upload_image_button", function() {
event.preventDefault();
var options, attachment;
$self = $(event.target);
$div = $self.closest('div.widget_image');
// if the frame already exists, open it
if (imageFrame) {
imageFrame.open();
return;
}
// set our settings
imageFrame = wp.media({
title: 'Choose Image',
multiple: false,
library: {
type: 'image'
},
button: {
text: 'Use This Image'
}
});
// set up our select handler
imageFrame.on('select', function() {
selection = imageFrame.state().get('selection');
if (!selection)
return;
// loop through the selected files
selection.each(function(attachment) {
console.log(attachment);
var src = attachment.attributes.sizes.full.url;
var id = attachment.id;
$div.find('.meta_box_upload_image_src').val(src);
$div.find('.meta_box_upload_image_preview').attr('src', src);
$div.find('.meta_box_upload_image').val(id);
});
});
// open the frame
imageFrame.open();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment