Sometimes you need data available to your scripts on the front end that you can normally only get from the server side of WordPress. Fortunately WordPress provides a relatively simple way to do this.

wp_localize_script() creates a global JavaScript object with the data it’s passed. It take three arguments:

  1. $handle
    The handle for the enqueued or registered script we want the data to be available to.
  2. $name
    The name of the global JavaScript object to be created, this can be anything.
  3. $data
    The data to pass to the script, this could simply be a string, or an associative array.

So passing a simple associative array would look something like this:

wp_localize_script('theme/js', 'dataObject', 
    'data' => 'Hello world!'

From within the theme/js script the data could then be accessed with the following.

// Would log 'Hello world!'

That’s it!

wp_localize_script() must be called after the script it’s passing data to has been registered using wp_register_script() or wp_enqueue_script().