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.

I have a problem adding a custom script to my functions.php file:

add_action('wp_print_scripts', 'load_AJAX_URL__');
function load_AJAX_URL__() {
    wp_localize_script( 'ajax_URL', 'MyAjax', array( 'ajaxurl' => admin_url('admin-ajax.php') ) );
}

Why is not working? any ideas?

share|improve this question
    
Do you want to use a variable in a js file? –  Joshua Abenazer Dec 21 '11 at 18:26
    
yes, that's I want to do. –  greenbandit Dec 21 '11 at 18:38
    
Please post more of the associated code so we don't have to guess what you have or havn't done..(ie. whether you've register and enqueued scripts). –  t31os Dec 21 '11 at 21:47

2 Answers 2

up vote 3 down vote accepted

The function wp_localize_script() is used to send variables to a script that has already been registered and enqueued. Do you have a js file that has been registered and enqueued and has the handle of 'ajax_URL'? If not, then that explains why it isn't working.

Also, ajaxurl is already a js variable that is accessible via any scripts you enqueue, so I'm not quite sure what you're trying to do here.

If you're just trying to add a new js file into your theme, you want to look at the wp_enqueue_script() function.

share|improve this answer
    
Im Trying to add a variable to use in two different javascripts pointing the same ajax url file. –  greenbandit Dec 21 '11 at 18:37
    
The variable you are trying to pass through is already available by default. –  Kevin Langley Jr. Dec 21 '11 at 18:42
    
Per the codex: Since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php codex.wordpress.org/AJAX_in_Plugins –  Kevin Langley Jr. Dec 21 '11 at 18:42
    
Also, keep in mind that like I said, the first paramater in the function wp_localize_script is the handle for the registered js file you are trying to localize. –  Kevin Langley Jr. Dec 21 '11 at 18:44
    
thank you, reading the codex . –  greenbandit Dec 21 '11 at 20:13

Ok you can do it this way.

function my_ajax_scripts() {
    $data = array( 'ajaxurl' => admin_url('admin-ajax.php') );
    wp_enqueue_script( 'ajax_url', get_stylesheet_directory_uri() . '/my-custom-ajax.js' );
    wp_localize_script( 'ajax_url', 'MyAjax', $data );
    wp_enqueue_script( 'ajax_url_2', get_stylesheet_directory_uri() . '/my-custom-ajax-2.js' );
    wp_localize_script( 'ajax_url_2', 'MyAjax', $data );
}
add_action( 'wp_enqueue_scripts', 'my_ajax_scripts' );

You need to enqueue the scripts first and then use wp_localize_script to pass a variable to that file using the handle of that particular js file.

share|improve this answer

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.