Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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');
like image 847
Max Avatar asked Jan 21 '17 13:01

Max


3 Answers

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.

like image 168
Max Avatar answered Oct 21 '22 14:10

Max


put the wp_enqueue_media function in your enqueue scripts function.

Example:

add_action('wp_enqueue_scripts', 'prince_load_scripts');

function prince_load_scripts(){
wp_enqueue_media();
//Yor scripts goes here...
}
like image 32
Prince Ahmed Avatar answered Oct 21 '22 15:10

Prince Ahmed


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. It turned out the content on this page was too massive, my PHP Memory Limit was to low. Setting up MemoryLimit 256->512 worked for me...

like image 1
chakmear Avatar answered Oct 21 '22 16:10

chakmear