0

This is my code:

wp_enqueue_script('ms_ajax_localized');

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

I popped it into my functions.php

Bashing my head against the wall. I've used wp_localize_script before and I'm just blind to what is wrong this time.

When I load the page I can't find the script tag in the source anywhere...

0

1 Answer 1

5

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.

3
  • I had an unnecessary condition around my enqueue_script. Thanks for the help. Commented Mar 24, 2013 at 20:08
  • @s_ha_dum Tried your code but it doesn't seem to be working. I want to add some PHP vars to be used with JS without tying it to a specific script.. And nothing gets printed by your suggestion. Hm.
    – INT
    Commented Dec 16, 2013 at 0:47
  • You have to tie it to a script. Not especially found of it but that is how wp_localize_script works.
    – s_ha_dum
    Commented Dec 16, 2013 at 1:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.