可以找到类似的问题here 和here. 我使用以下方法,改编自here:
主题/插件初始化时:
wp_enqueue_media();
用Javascript处理媒体对话框:
var wp_media_dialog_field;
function selectMedia() {
var custom_uploader;
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
});
custom_uploader.on(\'select\', function() {
attachment = custom_uploader.state().get(\'selection\').first().toJSON();
wp_media_dialog_field.val(attachment.url);
});
custom_uploader.open();
}
在Javascript中绑定一些按钮以显示媒体对话框并存储将接受返回值的字段:
jQuery(\'#my_button_1\').click(function(e) {
e.preventDefault();
wp_media_dialog_field = jQuery(\'#my_field_1\');
selectMedia();
});
jQuery(\'#my_button_2\').click(function(e) {
e.preventDefault();
wp_media_dialog_field = jQuery(\'#my_field_2\');
selectMedia();
});