编辑:脚本的其他变体似乎也不起作用,wp_enqueue_media()没有问题,但看起来不包括包含wp.media的脚本.
我正在尝试在自定义插件中使用Wordpress Media Uploader,但不断收到以下错误:
TypeError: undefined is not an object (evaluating 'wp.media.frames')
我的Javascript代码:
jQuery(document).ready(function(){
var mediaUploader;
jQuery('#upload-button').click(function(e) {
e.preventDefault();
// If the uploader object has already been created, reopen the dialog
if (mediaUploader) {
mediaUploader.open();
return;
}
// Extend the wp.media object
mediaUploader = wp.media.frames.file_frame = wp.media({
title: 'Choose Image',
button: {
text: 'Choose Image'
}, multiple: false });
// When a file is selected, grab the URL and set it as the text field's value
mediaUploader.on('select', function() {
var attachment = mediaUploader.state().get('selection').first().toJSON();
jQuery('#logo').val(attachment.url);
});
// Open the uploader dialog
mediaUploader.open();
});
});
.js文件注册如下:
/* Add the media uploader script */
function my_media_lib_uploader_enqueue() {
wp_enqueue_media();
wp_register_script( 'media-lib-uploader-js', plugins_url( 'media-lib-uploader.js' , __FILE__ ), array('jquery') );
wp_enqueue_script( 'media-lib-uploader-js' );
}
add_action('admin_enqueue_scripts', 'my_media_lib_uploader_enqueue');
解决方法:
解决了问题,问题在于wp_enqueue_media();将脚本调用到页面的页脚.因为我在某处使用了die()函数,所以没有加载脚本.