0

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?

3
  • Do you want to use a variable in a js file? Dec 21, 2011 at 18:26
  • yes, that's I want to do. Dec 21, 2011 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, 2011 at 21:47

2 Answers 2

3

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.

5
  • Im Trying to add a variable to use in two different javascripts pointing the same ajax url file. Dec 21, 2011 at 18:37
  • The variable you are trying to pass through is already available by default. Dec 21, 2011 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 Dec 21, 2011 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. Dec 21, 2011 at 18:44
  • Not sure if it's changed, but last time i worked with Ajax in WordPress i realised the ajax URL isn't defined front side(admittedly it could possibly have changed in current versions), if you want to work with Ajax in the public facing part of your site you'll have to define the ajax url yourself(so that part of your answer is only true whilst performing ajax actions admin side). Just an FYI.. ;)
    – t31os
    Dec 21, 2011 at 21:50
2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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