Last active
December 1, 2017 22:36
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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' ) ); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
// custom fields library
https://gist.github.com/Magnacarter/ad8e2fa66fd2018017165ffe573a9067
// implement library
https://gist.github.com/Magnacarter/198ab650752f48850735f9478ced2eb0