The wp_localize_script function is primarily used to allow WordPress to translate strings into multiple languages. It has another, more useful, ability though; it allows you to pass any data you like from your PHP scripts to your Javascripts. A common use case for wp_localize_script is to hand your javascripts the path to your plugin. Here’s the code for the impatient, we’ll dig into the details in a moment:
wp_register_script('acf-input-filter', $this->settings['dir'] . 'js/input.js', array('acf-input'), $this->settings['version']); wp_localize_script('acf-input-filter', 'acf_filter', array( 'plugin_dir' => plugins_url('',__FILE__)) );
Alright, lets break this code down a bit.
Line 1 registers your javascript with WordPress for inclusion in your pages. The first argument of wp_register_script is the handle for your script, which you’ll need for wp_localize_script. You cannot pass data to a script which has not yet been registered with wp_register_script. The order matters.
Line 2 is where we pass the data to the script we just registered. In order, the arguments are:
- The handle of the registered script you want to pass data to.
- The name of the Javascript object that the data will be stored in.
- An array of data to pass into your script.
That’s all it takes as far as the PHP is concerned.
Now lets move to the Javascript to access the data we just passed.
In the example above, we passed the current plugin’s url to our acf-input-filter Javascript. On any page where that script is loaded, we can now access that data just by typing:
acf_filter.plugin_dir
Any data you pass through the array is added to the object for use in your scripts. It’s really that easy.