简体   繁体   English

wp.​​media 使用 Wordpress Media Uploader 未定义

[英]wp.media undefined using Wordpress Media Uploader

Edit: Other variations of scripts don't seem to work either, the wp_enqueue_media() goes alright, but it looks like the script that includes the wp.media is not included.编辑:脚本的其他变体似乎也不起作用, wp_enqueue_media() 没问题,但看起来包含 wp.media 的脚本不包括在内。

I'm trying to use the Wordpress Media Uploader in a custom plugin, but keep getting the following error:我正在尝试在自定义插件中使用 Wordpress Media Uploader,但不断收到以下错误:

TypeError: undefined is not an object (evaluating 'wp.media.frames')

My Javascript-code:我的 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();
  });

});

The .js files are registered as follows: .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');

Solved the problem, the problem was that wp_enqueue_media();问题解决了,问题出在 wp_enqueue_media(); calls the scripts into the footer of the page.将脚本调用到页面的页脚中。 Because I was using a die() function somewhere, the scripts weren't loaded.因为我在某处使用了 die() 函数,所以没有加载脚本。

put the wp_enqueue_media function in your enqueue scripts function.wp_enqueue_media函数放在您的入队脚本函数中。

Example:例子:

add_action('wp_enqueue_scripts', 'prince_load_scripts');

function prince_load_scripts(){
wp_enqueue_media();
//Yor scripts goes here...
}

I also had a similiar problem... The scripts didn't load on one specific page, especially the scripts wp-media, which lead to the error "wp.media is not defined"... all the solutions didn't work.我也有一个类似的问题......脚本没有加载到一个特定的页面上,尤其是脚本 wp-media,导致错误“wp.media 未定义”......所有解决方案都不起作用. It turned out the content on this page was too massive, my PHP Memory Limit was to low.原来这个页面的内容太大了,我的PHP内存限制太低了。 Setting up MemoryLimit 256->512 worked for me...设置 MemoryLimit 256->512 对我有用...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM