wp_localize_script not working with jquery handle

I’m trying to spoof the jquery handle as I use grunt / bower in my WP projects to create concatenated minified builds of all my plugins and scripts. I’d like to include jQuery 2.1.3 within this, and dequeue the older version of jquery that ships with wordpress, but in order to make sure other plugins work I thought to (maybe in a bit of a hacky way) use the jquery handle for my script.

Unfortunately it seems like localize script wont fire though. What I’m doing is this :

Read More
    wp_deregister_script('jquery'); 

    wp_register_script( 'jquery', get_template_directory_uri().'/public/js/all.min.js', array(), false, true );

    wp_enqueue_script( 'jquery' );

    $localize_data = array(
    ....all the stuff I need in my scripts....
    );
    wp_localize_script( 'jquery', 'nona', $localize_data );

This is obviously wrapped in a function thats called on the appropriate hook, it works with a custom handle, but then there are compatibility issues, any ideas other than just creating an a array and converting it to a javascript object manually?

any help would be appreciated.

Related posts

Leave a Reply

1 comment

  1. The function wp_localize_script calls wp_scripts()->localize, and at the top of that function there is this:

    if ( $handle === 'jquery' )
        $handle = 'jquery-core';
    

    It changes the handle to jquery-core, so going to see where the default scripts are registered we find that jquery doesn’t reference the javascript file directly but via the dependencies jquery-core and jquery-migrate:

    // jQuery
    $scripts->add( 'jquery', false, array( 'jquery-core', 'jquery-migrate' ), '1.11.2' );
    $scripts->add( 'jquery-core', '/wp-includes/js/jquery/jquery.js', array(), '1.11.2' );
    $scripts->add( 'jquery-migrate', "/wp-includes/js/jquery/jquery-migrate$suffix.js", array(), '1.2.1' );
    

    I would try to change the handle to jquery-core, something like this:

    add_action('wp_enqueue_scripts', 'jquery_localized', 1);
    
    function jquery_localized() {
        wp_deregister_script('jquery');
        wp_deregister_script('jquery-core');
    
        wp_enqueue_script( 'jquery-core', get_template_directory_uri().'/public/js/all.min.js', array(), false, true );
    
        $localize_data = array(
        // ....all the stuff I need in my scripts....
        );
        wp_localize_script( 'jquery-core', 'nona', $localize_data );
    
        // this for compatibility purpose
        wp_register_script( 'jquery', false, array( 'jquery-core' ), false, true );
    }
    

    Note that I added 1 as priority to execute this function before others on the same hook.