从媒体上传器获取缩略图的URL

时间:2013-08-28 作者:Jay

我想从WordPress 3.5媒体上传程序中选择图像。我可以使用以下代码获取图像URL,但它会获取全尺寸图像。我想获取缩略图url,如何获取?

 var custom_uploader;
 $(\'.upload-image\').click(function(e) {
        e.preventDefault();

        if (custom_uploader) {
            custom_uploader.open();
            return;
        }

        custom_uploader = wp.media.frames.file_frame = wp.media({
            title: \'Choose Image\',
            button: {
                text: \'Choose Image\'
            },
            multiple: false
        });

        //When a file is selected, grab the URL
        custom_uploader.on(\'select\', function() {
            attachment = custom_uploader.state().get(\'selection\').first().toJSON();
            var abc = attachment.url;    //this is full image url. 
            alert (abc);
        });

        custom_uploader.open(); 
    });

3 个回复
SO网友:Lafif Astahdziq

您可以通过以下方式调试附件的结果:

console.log(attachment); 
如果缩略图大小可用,可以使用以下方法检索:

 var thumb = attachment.sizes.thumbnail.url;
 alert(thumb);

SO网友:random_user_name

我在自己的研究中发现了这个问题,并最终开发了一个更丰富的解决方案,我认为这可能是有价值的。

如果您想知道用户选择的媒体大小的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....
    }
});

SO网友:JohnC

您必须调用服务器来运行一些PHP。

$thumb_src = wp_get_attachment_image_src( $id, \'thumbnail\' );
其中$id是附件的id

附件属性。custom\\u uploader select函数中的id将为您提供值。您可以通过ajax调用将其发回,并通过这种方式获得缩略图url。

结束