Skip to content

Localise JS Scripts

Localise in WordPress is used to pass PHP data to JavaScript code. Despite its name suggesting localisation (i.e., translation), its primary purpose is to make PHP variables available to JavaScript.

The boilerplate already defines some variables which are useful such as:

  • AJAX url
  • Rest url
  • Custom defined rest routes

To add your own variable open app/Hook/LocaliseAssetsHook.php and add your variables like so:

app/Hook/LocaliseAssetsHook.php
wp_localize_script(Config::getInstance()->getKey('assets.vite.entrypoints.lumbermill'), 'LUMBERMILL_GLOBAL', [
'ajax_url' => admin_url('admin-ajax.php'),
'rest_url' => rest_url(),
'rest_routes' => $this->getRestRoutes()
'hello' => 'world'
]);

now to use it in your JS file do the following:

console.log(window.LUMBERMILL_GLOBAL.hello);

this will log ‘world’ to the console.