Calling wp_enqueue_media() in a custom theme widget on WordPress 3.5.x cause js error

I am writing a custom widget for my own WordPress theme.

From WordPress 3.5 there is a new Media Uploader instead of the old ThickBox.

Read More

My widget used to work fine on WordPress versions older than 3.5, but now the new media uploader prevent the old working behavior.

I added a check in the costructor for the presence of wp_enqueue_media function:

if( function_exists( 'wp_enqueue_media' ) ) {
    wp_enqueue_media();
}

but when this part of cose is executed javascript throw an error in the console stopping Js engine:

Uncaught TypeError: Cannot read property 'id' of undefined    load-scripts.php:69

I removed all the widget code and reduced it to bare bones… the error is caused by wp_enqueue_media() calls, but I cannot get my head around why and how to fix it.

I also read WordPress 3.5 custom media upload for your theme options, but there is no mention to this issue

Can anyone point me in the right direction? Is there any documentation available for the the WordPress 3.5 Media Uploader?

Related posts

Leave a Reply

4 comments

  1. It’s too late for you now, but might be helpful for other people. I managed to make it work using

    add_action( 'admin_enqueue_scripts', 'wp_enqueue_media' );

    Hope it helps!

  2. The problem you are experiencing is because you probably put your custom jquery in the header and you didn’t registered wordpress jquery. If multiple jquery are defined you will get that error.

    My sugestion is you should either remove your jquery script or remove the one from wordpress

    function remove_jquery() {
    
    wp_deregister_script('jquery');
    //wp_register_script('jquery', ("//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"), false);
    
    }
    
    if(!is_admin()){add_action('init', 'remove_jquery');}
    

    I suggest you use the jquery wordpress provides you, if not, the proper way to enqueue it is to deregister the default one an register your jquery. Just remove the comments from the remove_jquery function.

    Also, the above code should go in functions.php

    Cheers.

  3. To debug, you need to get the non-minified versions of the js sent to the browser. See the docs:

    SCRIPT_DEBUG

    SCRIPT_DEBUG is a related constant that will force WordPress to use the “dev” versions of core CSS and Javascript files rather than the minified versions that are normally loaded. This is useful when you are testing modifications to any built-in .js or .css files. Default is false.

    define('SCRIPT_DEBUG', true);