Your actual issue is that you are using $('.custom_media_url').val(attachment.url);
without selecting the exact field you need. This selects every .custom_media_url
field on the page, e.g. each field within each widget.
Since you are using jQuery, you can replace this line:
$('.custom_media_url').val(attachment.url);
with
$( e.target ).siblings( '.custom_media_url' ).val( attachment.url )
However, using wp.media.editor
is not the perfect function to use, as it’s meant to send images within the editor and this includes extra fields, like “link to” and etc. This is overkill for you.
I suggest trying the following snippet:
function media_upload( button_class ) {
$( 'body' ).on( 'click', button_class, function( e ) {
var $button = $( this ), frame;
e.preventDefault();
// Create a proper popup for selecting an image
frame = wp.media({
title: 'Select image',
multiple: false,
button: {
text: 'Use this image'
}
});
// Add a callback for when an item is selected
frame.state( 'library' ).on( 'select', function(){
var image = this.get( 'selection' ).first();
// Inspect the image variable further
// console.log( image.toJSON() )
// Save the actual URL within the input
$button.siblings( '.custom_media_url' ).val( image.get( 'url' ) );
});
// Finally, open the frame
frame.open();
});
}
This will use a proper media selection popup and although you would use the option to choose an image size there, there will be no meaningless options there either. Please keep in mind that I have not tested this code for errors.