wp_localize_script with handle jquery - wordpress

2019-09-03 11:47发布

问题:

I'm looking for next solution. I want faster website so I concat all JS to one file and placed in footer. One of my js is jQuery and I use next hook and function:

if (!function_exists("ef_theme_scripts")) {

    function ef_theme_scripts() {
        wp_deregister_script('jquery'); 
        wp_register_script('jquery', get_template_directory_uri() . '/js/min/script.min.js', null, null, true);
        wp_enqueue_script('jquery');
        $params = array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'ajax_nonce' => wp_create_nonce('user_nonce'),
        );
        wp_localize_script( 'jquery', 'ajax_object', $params );         
    }

}
add_action('wp_enqueue_scripts', 'ef_theme_scripts');

I called my handle "jquery" because there can be some scripts (e.g. from plugins) which wants use jquery so I need add called this handle "jquery".

Everything works great except localize. When I rename script handle for example to "custom-jquery" then wp_localize_script works without problem.

I use WP 4.0.1. Thanks for help

回答1:

IMPORTANT! wp_localize_script() MUST be called after the script it's being attached to has been registered using wp_register_script() or wp_enqueue_script().

More info



回答2:

I asked a similar question and got the working solution here :

wp_localize_script not working with jquery handle

Basically this has to do with the way that WP works with the jQuery handle, you'll need to

  1. deregister jquery
  2. deregister jquery-core
  3. Use the jquery-core handle on your script
  4. at the end register jquery, with a dependency on jquery-core and passing false for the $scr attribute

Code:

wp_register_script( 'jquery', false, array( 'jquery-core' ), false, true );