Skip to content

Instantly share code, notes, and snippets.

@cameronjonesweb
Created April 25, 2020 02:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cameronjonesweb/bd98a552668b204be9156d7709297e8a to your computer and use it in GitHub Desktop.
Save cameronjonesweb/bd98a552668b204be9156d7709297e8a to your computer and use it in GitHub Desktop.
Upload media to a custom input in the WordPress admin
jQuery(document).ready(function($){
var custom_uploader;
var $btn;
$('.image_upload_button').click(function(e) {
$btn = $(this);
e.preventDefault();
//If the uploader object has already been created, reopen the dialog
if (custom_uploader) {
custom_uploader.open();
return;
}
//Extend the wp.media object
custom_uploader = wp.media.frames.file_frame = wp.media({
title: 'Choose Image',
button: {
text: 'Choose Image'
},
multiple: false
});
//When a file is selected, grab the URL and set it as the text field's value
custom_uploader.on('select', function() {
attachment = custom_uploader.state().get('selection').first().toJSON();
console.log(attachment.url);
console.log($($btn).siblings());
$($btn).siblings('.image_upload_value').val(attachment.url);
$($btn).siblings('.image_upload_preview').attr("src", attachment.url)
});
//Open the uploader dialog
custom_uploader.open();
});
$('.image_upload_clear').click(function(e) {
e.preventDefault();
$(this).siblings('.image_upload_value').val('');
$(this).siblings('.image_upload_preview').attr("src", '')
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment