我在自己的研究中发现了这个问题,并最终开发了一个更丰富的解决方案,我认为这可能是有价值的。
如果您想知道用户选择的媒体大小的url,那么以下代码(下面是完整的jQuery代码)将为您提供:
jQuery(function($) {
// Bind to my upload butto
$(document).on(\'click\', \'a.custom-media-upload\', function() {
customUpload($(this));
return false;
});
function customUpload(el) {
formfield = $(el);
custom_media = true;
var _orig_send_attachment = wp.media.editor.send.attachment;
wp.media.editor.send.attachment = function(props, attachment) {
if ( custom_media ) {
formfield = renderUpload(formfield, attachment, props);
} else {
return _orig_send_attachment.apply( this, [props, attachment] );
}
}
wp.media.editor.open(1);
}
function renderUpload(field, attachment, props) {
// This gets the full-sized image url
var src = attachment.url;
// Get the size selected by the user
var size = props.size;
// Or, if you\'d rather, you can set the size you want to get:
// var size = \'thumbnail\'; // or \'full\' or \'medium\' or \'large\'...
// If the media supports the selected size, get it
if (attachment.sizes[size]) {
src = attachment.sizes[size].url;
}
// Do what you want with src here....
}
});