Categories
Uncategorized

Localizing Scripts In WordPress

The title of this post translates to “passing data from PHP files to JavaScript files in WordPress development environment”. This can be done by using a function called wp_localize_script in WordPress.

In this example, $script_atts is being passed to the JS file as “settings”. It is then passed to the in-place executing function in test.js as “window.settings” and finally used as “settings” within the JS function.

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.

PHP

If you’d like pass some array (say script-atts) to 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 )

JS

Then finally it can be used in test.js as follows:

  • By creating a function that accepts window.data_label as one of its arguments (where data_label is what we labelled or named the data in wp_localize_script function).

Bonus

The JS example I used in my notes above demonstrates a function that executes in place.

Leave a Reply

Your email address will not be published. Required fields are marked *