News & Info

Daily Updates and Tech Chatter

Passing PHP Variables to JavaScript

One of the things we do fairly frequently in our WordPress plugins is pass PHP variables to JavaScript.   We use this methodology to send a number of dynamic elements to the JavaScript processor without having to do AJAX or JSONP calls after the script has loaded.  Pre-processing and passing variables into JavaScript when the script is loaded is a far simpler mechanism.

 WordPress provides a simple, yet oft overlooked, method for getting your PHP data into JavaScript.   Using wp_localize_script() quickly maps a PHP named array to similar structure in JavaScript.    To do so you follow two simple steps:

1) Register or Enqueue your script.
see: http://codex.wordpress.org/Function_Reference/wp_enqueue_script

2) Localize your script.
see: http://codex.wordpress.org/Function_Reference/wp_localize_script

We have found some caveats for some themes.   Most importantly, make sure you select for “late loading” or “load in footer” so the script can be localized BEFORE it is rendered in the browser.  The other option is to register the script using wp_register_scripts() in the wp_enqueue_scripts hook then later load the script in a wp_footer hook using wp_enqueue_scripts().     Just keep in mind that not all themes support wp_footer().

Tags: , , ,

Comments are closed.