使用媒体上传工具获取上传图片的所有URL

时间:2016-10-09 作者:martin49

我需要使用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);
        });
});
});

1 个回复
最合适的回答,由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);
        });
});
});

相关推荐

JQuery php请求返回一个奇怪的结果

我有一个奇怪的小故障发生在我身上,我不知道我是如何产生它的,或者它是否是正常的。我正在开发自己的插件,当一个足球队/足球队被输入到一个框中时,它会检查它是否已经在数据库中。以下是我的代码行add_action( \'admin_footer\', \'fws_teamcheck_javascript\' ); function fws_teamcheck_javascript() { ?> <script type="text/javascript">