Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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...

share|improve this question

1 Answer 1

up vote 1 down vote accepted

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.

share|improve this answer
    
I had an unnecessary condition around my enqueue_script. Thanks for the help. –  jackreichert Mar 24 '13 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 Dec 16 '13 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 Dec 16 '13 at 1:12

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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