我需要使用WP media uploader在插件中上载多个图像。我发现这段代码适用于单个图像。我试过换衣服multiple: false
为true,这使我能够在媒体上载程序中选择多个图像。我的问题是,我不知道如何获取所有上传图像的URL,而不仅仅是附加代码中的URL。我试过换衣服var uploaded_image = image.state().get(\'selection\').first();
到var uploaded_image = image.state().get(\'selection\')
然后用这段代码迭代数组,但没有成功。
var uploaded_image = image.state().get(\'selection\').first();
jQuery.each(uploaded_image, function (i) {
console.log(uploaded_image[i].toJSON().url);
});
原始代码:
jQuery(document).ready(function($){
$(\'#upload-btn\').click(function(e) {
e.preventDefault();
var image = wp.media({
title: \'Nahranie obsahu\',
// mutiple: true if you want to upload multiple files at once
multiple: false
}).open()
.on(\'select\', function(e){
// This will return the selected image from the Media Uploader, the result is an object
var uploaded_image = image.state().get(\'selection\').first();
// We convert uploaded_image to a JSON object to make accessing it easier
// Output to the console uploaded_image
// console.log(uploaded_image);
var image_url = uploaded_image.toJSON().url;
// Let\'s assign the url value to the input field
$(\'#image_url\').val(image_url);
});
});
});
最合适的回答,由SO网友:martin49 整理而成
用这个问题中的代码工作https://stackoverflow.com/questions/14847668/get-url-of-freshly-uploaded-image-from-wp3-5-media-uploader
也许有人会发现它很有用。这段代码将每个新上传的图像的URL记录到控制台。
jQuery(document).ready(function($){
$(\'#upload-btn\').click(function(e) {
e.preventDefault();
var image = wp.media({
title: \'Nahranie obsahu\',
// mutiple: true if you want to upload multiple files at once
multiple: true
}).open()
.on(\'select\', function(e){
// This will return the selected image from the Media Uploader, the result is an object
var uploaded_images = image.state().get(\'selection\');
var attachment_ids = uploaded_image.map( function( attachment ) {
attachment = attachment.toJSON();
console.log(attachment.url);
}).join();
// We convert uploaded_image to a JSON object to make accessing it easier
// Output to the console uploaded_image
// console.log(uploaded_image);
var image_url = uploaded_image.toJSON().url;
// Let\'s assign the url value to the input field
$(\'#image_url\').val(image_url);
});
});
});