最合适的回答,由SO网友:Kevin W. 整理而成
我已经想出了更好的和新的工作版本,支持所有文件类型,我将在这里分享,以防其他人正在寻找这个答案。
已将输入字段添加到metabox
<input type="text" name="sermon_mp4" id="sermon_mp4" value="<?php echo $sermonmp4; ?>"/>
<input type="button" id="sermon_mp4_button" value="Add Sermon Audio" />
jQuery
<script type = "text/javascript">
// Uploading files
var file_frame;
jQuery(\'#sermon_mp4_button\').live(\'click\', function(podcast) {
podcast.preventDefault();
// If the media frame already exists, reopen it.
if (file_frame) {
file_frame.open();
return;
}
// Create the media frame.
file_frame = wp.media.frames.file_frame = wp.media({
title: jQuery(this).data(\'uploader_title\'),
button: {
text: jQuery(this).data(\'uploader_button_text\'),
},
multiple: false // Set to true to allow multiple files to be selected
});
// When a file is selected, run a callback.
file_frame.on(\'select\', function(){
// We set multiple to false so only get one image from the uploader
attachment = file_frame.state().get(\'selection\').first().toJSON();
var url = attachment.url;
var field = document.getElementById("sermon_mp4");
field.value = url; //set which variable you want the field to have
});
// Finally, open the modal
file_frame.open();
});
最后需要做的是包括wp\\u enqueue函数
function asp_admin_scripts() {
wp_enqueue_script(\'media-upload\');
wp_enqueue_script(\'thickbox\');
}
function asp_admin_styles() {
wp_enqueue_style(\'thickbox\');
}
add_action(\'admin_print_scripts\', \'asp_admin_scripts\');
add_action(\'admin_print_styles\', \'asp_admin_styles\');
}
如果元数据库中有多个字段需要使用媒体上载程序,只需从上面的jQuery中删除此文本并复制代码
// If the media frame already exists, reopen it.
if (file_frame) {
file_frame.open();
return;
}