gschoppe
2/28/2018 - 4:12 AM

WordPress Media Library JS snippet

USAGE: You may need to enqueue the media library to use this script.

add_action( 'admin_enqueue_scripts', function($hook) { wp_enqueue_media(); });

/**
USAGE:
<div class="gs_media_upload">
	<img src="path to the image you have saved">
	<input type="hidden" name="your-name-here">
	<button class="gs_media_upload_button" data-add-button="Add to plugin">Upload media</button>
</div>
**/

(jQuery)(function($){
	'use strict';
	$(window).ready(function(){
		$('body').on('click','.gs_media_upload_button', function() {
			var $button  = $(this);
			var $preview = $button.prev('img').eq(0);
			var $field   = $preview.prev('input').eq(0);
			var add_text = $button.data('add-button');

			var uploader = wp.media({
				title:   'Image Widget',
				multiple: false,
				library:  { type: 'image' },
				button:   { text: add_text }
			});
			uploader.on('close',function(){
				var attachments = uploader.state().get('selection').toJSON();
				if ( attachments.length < 1 ) {
					return; // nothing was chosen
				}
				var attachment = attachments[0];
				$field.val(attachment.id).trigger('change');
				$preview.attr('src', attachment.sizes['thumbnail'].url);
			});
			uploader.open();
			return false;
		});
	});
});