Skip to content

Instantly share code, notes, and snippets.

@afuggetta
Created June 25, 2015 19:44
Show Gist options
  • Save afuggetta/6dab2b577df9bc11d3eb to your computer and use it in GitHub Desktop.
Save afuggetta/6dab2b577df9bc11d3eb to your computer and use it in GitHub Desktop.
Javascript to handle a media upload
/* global jQuery, wp */
/**
* To enqueue in admin:
* $template_dir = get_template_directory_uri();
* //Enqueue necessary scripts for using WP JS media library
* wp_enqueue_media();
* //Custom JS for admin
* wp_enqueue_script( 'coresales-admin-scripts', $template_dir . '/javascripts/coresales_media_admin.min.js', array( 'jquery' ), 1.0, true );
*/
(function($) {
$(document).ready(function() {
var frame,
$imgContainer = $('#custom-img-container'),
$imgIdInput = $('#custom-img-id'),
$addImgLink = $('.add-custom-img'),
$delImgLink = $('.delete-custom-img');
$('#add-image-button').click( function(e){
e.preventDefault();
if( frame ){
frame.open();
return;
}
frame = wp.media.frames.meta_image_frame = wp.media({
title: 'TEST',
button: { text: 'BUTTON' },
library: { type: 'image' }
});
frame.on('select', function(){
var media_attachment = frame.state().get('selection').first().toJSON();
$('#taxonomy-image-thumb').val(media_attachment.sizes.thumbnail.url); // thumb
$('#taxonomy-image').val(media_attachment.url);
});
frame.open();
});
$addImgLink.on( 'click', function(){
if( frame ){
frame.open();
return;
}
frame = wp.media({
title: 'Select or Upload Media Of Your Chosen Persuasion',
button: { text: 'Use this media' },
library: { type: 'image' },
multiple: false // Set to true to allow multiple files to be selected
});
frame.on( 'select', function() {
var attachment = frame.state().get('selection').first().toJSON();
$imgContainer.html( '<img src="' + attachment.url.toString() + '" alt="" style="max-width:300px;"/>' );
$imgIdInput.val(attachment.id); // Send the attachment id to our hidden input
$addImgLink.addClass('hidden'); // Hide the add image link
$delImgLink.removeClass('hidden'); // Show the remove image link
});
frame.open();
});
$delImgLink.on( 'click', function( ){
$imgContainer.html( '' ); // Clear out the preview image
$addImgLink.removeClass( 'hidden' ); // Show the add image link
$delImgLink.addClass( 'hidden' ); // Hide the delete image link
$imgIdInput.val( '' ); // Delete the image id from the hidden input
});
if($imgIdInput.val() !== '') {
$addImgLink.addClass( 'hidden' ); // Show the add image link
$delImgLink.removeClass( 'hidden' ); // Hide the delete image link
}
});
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment