最近发布了 WordPress 3.5,我通过 thickbox 和 window.send_to_editor
使用了 WordPress Media Upload 系统来为我的 WordPress 主题(背景、 Logo 等...)中的一些选项。
但是正如您所知,WordPress 集成了一个新的媒体管理器,我想使用这个新功能将图像/文件作为自定义字段上传。所以我花了一上午的时间来寻找一种方法来获得想要的结果。
我找到了这个解决方案,它对你们中的一些人很有用。感谢您向我提供有关代码的反馈或您想到的任何改进!
HTML 示例:
<a href="#" class="custom_media_upload">Upload</a>
<img class="custom_media_image" src="" />
<input class="custom_media_url" type="text" name="attachment_url" value="">
<input class="custom_media_id" type="text" name="attachment_id" value="">
jQuery 代码:
$('.custom_media_upload').click(function() {
var send_attachment_bkp = wp.media.editor.send.attachment;
wp.media.editor.send.attachment = function(props, attachment) {
$('.custom_media_image').attr('src', attachment.url);
$('.custom_media_url').val(attachment.url);
$('.custom_media_id').val(attachment.id);
wp.media.editor.send.attachment = send_attachment_bkp;
}
wp.media.editor.open();
return false;
});
如果您想查看包含在attachment
变量中的每个设置,您可以执行console.log(attachment)
或alert(attachment)
.
最佳答案
您以一种意想不到的方式进行。您的 JavaScript 代码可能看起来像这样:
$('.custom_media_upload').click(function(e) {
e.preventDefault();
var custom_uploader = wp.media({
title: 'Custom Title',
button: {
text: 'Custom Button Text'
},
multiple: false // Set this to true to allow multiple files to be selected
})
.on('select', function() {
var attachment = custom_uploader.state().get('selection').first().toJSON();
$('.custom_media_image').attr('src', attachment.url);
$('.custom_media_url').val(attachment.url);
$('.custom_media_id').val(attachment.id);
})
.open();
});
关于jquery - WordPress 3.5 为您的主题选项自定义媒体上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13847714/