DevTeam-Admin
3/26/2020 - 11:04 PM

Localize Script in Wordpress

This functionality allows you to save PHP variables and have them accessible in Javascript. This way, for instance, you can set a value in an ACF field, and then use that value as a variable in Javascript.

/*
 * Localize Data for JS
 */
$rs_localize_script = array(
  'my_acf_image' => get_field('my_image),
  'specific_page_url' => home_url('/'),
  'admin_ajax' => admin_url('admin-ajax.php'),
);

/* we pass this function 3 things: 
* 1. the handle of the javascript file you want this data accessible in, as enqueued in your functions.php file
* 2. the name of the javascript object the data will be attached to
* 3. the name of the array above
*/
wp_localize_script('my-js-handle', 'objectNameForJs', $rs_localize_script);
const myImageUrl = objectNameForJs.my_acf_image; // access the image set in PHP
const myRedirectLink = objectNameForJs.specific_page_url; // access the url set in PHP

$.ajax({
  type: 'POST',
  url: objectNameForJs.admin_ajax, // this is how you make an ajax call in WP/JS
  data: {
    action: POST,
    image: myImageUrl,
    url: myRedirectLink
  }
}).done(function(data) {
  my_done_function();
})