1

I usually enable ajax in a js script by using wp_localize_script like this

wp_localize_script( 'map-scripts', 'ajax_info', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );

but now I see it is best practice to use wp_add_inline_script, which I find harder to use.

I am not able to pass an array with this method. I tried the following but it does not look the same:

$ajax_arr = array( 'ajax_url' => admin_url( 'admin-ajax.php' ) );
$ajax_json = json_encode($ajax_arr);
$ajax_info  = 'ajax_info = '.json_encode($ajax_json).';';
wp_add_inline_script( 'map-scripts', $ajax_info, 'before' );

Do you know the proper way to do it?

7
  • Where did you see that it was best practice to use that function? Commented Apr 29, 2021 at 9:13
  • have you considered using the REST API for ajax instead of the old admin ajax file?
    – Tom J Nowell
    Commented Apr 29, 2021 at 9:44
  • @JacobPeattie developer.wordpress.org/reference/functions/wp_localize_script/… says wp_add_inline_script() was introduced in WordPress Version 4.5, and is now the best practice for that use case
    – Marc
    Commented Apr 29, 2021 at 12:06
  • @TomJNowell yes! I have used it a couple of times, do you recommend it? I like it, but there is not as much documentation/community on it.
    – Marc
    Commented Apr 29, 2021 at 12:08
  • Personally I see no reason to use admin-ajax.php while the REST API exists
    – Tom J Nowell
    Commented Apr 29, 2021 at 14:32

1 Answer 1

3

If anyone still needs it:

wp_add_inline_script(
  'map-scripts',
  'const ajax_info = ' . json_encode(array(
      'ajaxurl' => admin_url('admin-ajax.php'),
   )),
  'before'
);

but, it's good practice to use nonce as well for better security:

wp_add_inline_script(
  'map-scripts',
  'const ajax_info = ' . json_encode(array(
      'ajaxurl' => admin_url('admin-ajax.php'),
      'nonce' => wp_create_nonce('your_nonce_handler'), //the more specific the better
      'your_other_item' => "some additional data", //etc.. 
   )),
  'before'
);

https://developer.wordpress.org/reference/functions/wp_add_inline_script/

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.