Skip to content

Instantly share code, notes, and snippets.

@hugosolar
Last active November 21, 2017 18:34
Show Gist options
  • Save hugosolar/6077109 to your computer and use it in GitHub Desktop.
Save hugosolar/6077109 to your computer and use it in GitHub Desktop.
Javascript class to use new wp.media uploader to upload or use an existing image to use it in the wordpress custom menu using this plugin idea https://github.com/blazersix/simple-image-widget
jQuery(function($) {
var $control;
mediaControl = {
// Initializes a new media manager or returns an existing frame.
// @see wp.media.featuredImage.frame()
frame: function() {
if ( this._frame )
return this._frame;
this._frame = wp.media({
title: 'Set image to menu element',
library: {
type: 'image'
},
button: {
text: 'Set image'
},
multiple: false
});
this._frame.on( 'open', this.updateFrame ).state('library').on( 'select', this.select );
return this._frame;
},
select: function() {
// Do something when the "update" button is clicked after a selection is made.
attachment = this.get('selection').first().toJSON();
var item_id = $control.data('itemid');
var img_obj = $control.data('targetimg');
var img_id = $control.data('targetid');
//this is defined in functions.php via wp_ajax action
$.post(ajaxurl,{action:'set_thumbnail',id:attachment.id,item:item_id}, function(data){
if (data == 1) {
console.log('done');
}
});
$('.'+img_obj).attr('src', attachment.sizes.thumbnail.url);
$('.'+img_id).val(attachment.id);
},
updateFrame: function() {
// Do something when the media frame is opened.
},
init: function() {
$('#menu-to-edit').on('click', '.set-post-thumbnail', function(e) {
e.preventDefault();
mediaControl.frame().open();
//use control to save click object
$control = $(this);
});
//delete function
$('#menu-to-edit').on('click','.remove-post-thumbnail', function( event ) {
event.preventDefault();
event.stopPropagation();
var obj = $(this);
var img_obj = obj.data('targetimg');
var item_id = obj.data('itemid');
//this is defined in functions.php via wp_ajax action
$.post(ajaxurl,{action:'delete_thumbnail',item:item_id}, function(data){
if (data == 1) {
$('.'+img_obj).attr('src', '');
$('#delete-link-'+item_id).hide();
}
});
});
}
};
jQuery(document).ready(function($){
if ( window.wp ) {
mediaControl.init();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment