Skip to content

Instantly share code, notes, and snippets.

@adamcrampton
Last active May 3, 2019 01:10
Show Gist options
  • Save adamcrampton/68ff7398e9ef59698e5f11e07d622d5d to your computer and use it in GitHub Desktop.
Save adamcrampton/68ff7398e9ef59698e5f11e07d622d5d to your computer and use it in GitHub Desktop.
WordPress - JS for uploading images to widget
/**
* Steps:
* 1. Pop this into your theme's assets/js directory, set the filename as widgets.js (or add JS to existing widgets.js)
* 2. See the other gist for widget PHP instructions if you haven't already
* 3. Profit++
*/
// ============================================
// Custom JavaScript used in Widgets (WP Admin)
// ============================================
// Image uploader
// https://vedmant.com/using-wordpress-media-library-in-widgets-options/
jQuery(document).ready(function ($) {
console.log('started');
$(document).on("click", ".upload_image_button", function (e) {
e.preventDefault();
var $button = $(this);
console.log('clicked');
// Create the media frame.
var file_frame = wp.media.frames.file_frame = wp.media({
title: 'Select or upload image',
library: { // remove these to show all
type: 'image' // specific mime
},
button: {
text: 'Select'
},
multiple: false // Set to true to allow multiple files to be selected
});
// When an image is selected, run a callback.
file_frame.on('select', function () {
// We set multiple to false so only get one image from the uploader
var attachment = file_frame.state().get('selection').first().toJSON();
$button.siblings('input').val(attachment.url);
});
// Finally, open the modal
file_frame.open();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment