使用wp.media创建自定义图像上载程序时出现WP未定义错误

时间:2016-11-01 作者:Christy

我正在尝试在自定义帖子类型的自定义元框中创建自定义媒体上载程序。这是很多习俗。我有一个运行wp的javascript文件排队。单击“添加图像”按钮时的媒体类。测试按钮时,我收到以下错误:“Uncaught ReferenceError:wp is not defined”(未捕获引用错误:wp is not defined),我发现有几个资源通过添加wp\\u enqueue\\u media()解决了此问题;但当我尝试这样做时,它并不能解决问题。请帮忙?

Meta box creation/enqueued script:

function cns_add_custom_metabox(){
    add_meta_box( \'fet-media-fields\', \'Listing Media\', \'cns_display_media\' );
}
add_action( \'add_meta_boxes\', \'cns_add_custom_metabox\' ); 

function cns_display_media( $post ){ 

    ?>

    <div id="metabox-wrapper">
        <img id="image-tag">
        <input type="hidden" id="img-hidden-field" name="custom_image_data">
        <input type="button" id="image-upload-button" class="button" value="Add Image">
        <input type="button" id="image-delete-button" class="button" value="Remove Image">

    </div>


    <?php
}

function register_admin_script() {
    wp_enqueue_script( \'cns-image-upload.js\', get_stylesheet_directory_uri() . \'/js/cns-image-upload.js\', array(\'jquery\') );
}

add_action( \'admin_enqueue_scripts\', \'register_admin_script\' );

Javascript file - cns-image-upload.js:

var addButton = document.getElementById( \'image-upload-button\' );
var deleteButton = document.getElementById( \'image-delete-button\' );
var img = document.getElementById( \'image-tag\' );
var hidden = document.getElementById( \'img-hidden-field\' );
var customUploader = wp.media({
    title: \'Select and Image\',
    button:{
        text: \'User this Image\'
    },
    multiple: false
});

addButton.addEventListener( \'click\', function(){
    if( customUploader ){
        customUploader.open();
    }
} );

1 个回复
SO网友:Christy

算了吧!我没有用以下代码包装javascript代码:

jQuery(document).ready( function($){ });