Can’t seem to get wp_localize_script to work

I tested that code like this:

wp_enqueue_script('jquery');

wp_localize_script( 'jquery', 'MS_Ajax', array(
    'ajaxurl'       => admin_url( 'admin-ajax.php' ),
    'nextNonce'     => wp_create_nonce( 'myajax-next-nonce' ))
);

And it works but throws a Notice. It should be hooked to wp_enqueue_scripts like:

function my_enqueue_scripts() {
    wp_enqueue_script('jquery');
    wp_localize_script( 'jquery', 'MS_Ajax', array(
        'ajaxurl'       => admin_url( 'admin-ajax.php' ),
        'nextNonce'     => wp_create_nonce( 'myajax-next-nonce' ))
    );
}
add_action('wp_enqueue_scripts','my_enqueue_scripts');

You have to have your script registered and enqueued correctly before you use wp_localize_script. Since the code I tested, using the Core supplied jquery works, I have to assume that that is the problem. Your script registration, which I don’t see at all, or script enqueueing is going bad and thus wp_localize_script script isn’t working.

Leave a Comment