wp.media undefined using Wordpress Media Uploader

Max picture Max · Jan 21, 2017 · Viewed 12k times · Source

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.

I'm trying to use the Wordpress Media Uploader in a custom plugin, but keep getting the following error:

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

My Javascript-code:

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:

/* 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');

Answer

Max picture Max · Jan 28, 2017

Solved the problem, the problem was that 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.