Skip to content

Instantly share code, notes, and snippets.

@Magnacarter
Last active December 1, 2017 22:36
Show Gist options
  • Save Magnacarter/68259b98590027bdb4d55596e8f2f53c to your computer and use it in GitHub Desktop.
Save Magnacarter/68259b98590027bdb4d55596e8f2f53c to your computer and use it in GitHub Desktop.
JS needed for WordPress modal for media uploads. Use wp_enqueue_media(); in your enqueue function to get the modal to show
jQuery( function( $ ) {
"use strict";
/**
* Open media library in modal
*/
function imageModal( metaBoxSelector ) {
let frame,
metaBox = $( metaBoxSelector ),
addImgLink = metaBox.find('.upload-custom-img'),
delImgLink = metaBox.find('.delete-custom-img'),
imgContainer = metaBox.find('.custom-img-container'),
imgIdInput = metaBox.find('.custom-img-id');
// ADD IMAGE LINK
addImgLink.on('click', function (e) {
e.preventDefault();
// If the media frame already exists, reopen it.
if (frame) {
frame.open();
return;
}
// Create a new media frame
frame = wp.media({
title: 'Select or Upload Media Of Your Chosen Persuasion',
button: {
text: 'Use this media'
},
multiple: false // Set to true to allow multiple files to be selected
});
frame.on('select', function () {
let attachment = frame.state().get('selection').first().toJSON();
imgContainer.append('<img src="' + attachment.url + '" alt="" style="max-width:100%;"/>');
imgIdInput.val(attachment.id);
addImgLink.addClass('hidden');
delImgLink.removeClass('hidden');
});
frame.open();
});
// DELETE IMAGE LINK
delImgLink.on('click', function (event) {
event.preventDefault();
imgContainer.html('');
addImgLink.removeClass('hidden');
delImgLink.addClass('hidden');
imgIdInput.val('');
});
}
// Image modal for Region cpt posts
imageModal( $( '#region.postbox' ) );
// Image modal for Licensee users
imageModal( $( '.form-table' ) );
});
@Magnacarter
Copy link
Author

Magnacarter commented Dec 1, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment