I have this code which works perfectly if you use a single widget. However if you create another widget the uploader will overwrite both widgets settings.
Does anyone know how this script can be modified to allow it to be used multiple times?
HTML
<p>
<label for="<?php echo $this->get_field_name( 'image_url' ); ?>"><?php _e( 'Category Image:', 'text-domain' ); ?></label>
<input name="<?php echo $this->get_field_name( 'image_url' ); ?>" id="<?php echo $this->get_field_id( 'image_url' ); ?>" class="widefat img custom_media_url" type="text" size="36" value="<?php echo esc_url( $image_url ); ?>" />
<input class="custom_media_upload" id="custom_media_button" type="button" value="<?php esc_attr_e('Upload Image', 'text-domain'); ?>" />
</p>
Javascript:
jQuery(document).ready( function($) {
function media_upload(button_class) {
var _custom_media = true,
_orig_send_attachment = wp.media.editor.send.attachment;
$('body').on('click', button_class, function(e) {
var button_id ='#'+$(this).attr('id');
var self = $(button_id);
var send_attachment_bkp = wp.media.editor.send.attachment;
var button = $(button_id);
var id = button.attr('id').replace('_button', '');
_custom_media = true;
wp.media.editor.send.attachment = function(props, attachment){
if ( _custom_media ) {
$('.custom_media_url').val(attachment.url);
} else {
return _orig_send_attachment.apply( button_id, [props, attachment] );
}
}
wp.media.editor.open(button);
return false;
});
}
media_upload('.custom_media_upload');
});