wp_localize_script in WordPress.
Let’s say you have a JS file called
test.js located at
assets/js/tests.js and some PHP file located in the root directory of your project.
If you’d like pass some array (say
test.js, you can do so in three steps:
- Register the script:
wp_register_script( script_label, script_location )
- Localize the script:
wp_localize_script( script_label, data_label, the_actual_data )
- Enqueue the script:
wp_enqueue_script( script_label )
Then finally it can be used in
test.js as follows:
- By creating a function that accepts
window.data_labelas one of its arguments (where data_label is what we labelled or named the data in wp_localize_script function).
The JS example I used in my notes above demonstrates a function that executes in place.