News & Info

CSA 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: , , ,

About Lance Cleveland

I started my high-tech career in the early 80's as a computer technician. I became a lead engineer at a Boston area database company a few years later. When the Internet was just starting to show up on people's radar I quit my corner-office job and founded ProActive Web Marketing, my first start up company. That was the genesis of several successful start up companies including Time Magazine award winner The Lobster Net. After brief retirement in my mid-30s I co-founded the software consulting firm, Cyber Sprocket Labs. In addition to being "man of all hats" at Charleston Software Associates, I currently serve on the board or as technical adviser for several companies including Musiplicity, Model Locate, and Advanced Media Ltd. In the past I consulted for Data General, Kimberly Clark, Kraft, Philip Morris, Rich Foods, Telefonica, Aribtron, and a half-dozen other Fortune 500 companies. I've appeared as a keynote speaker for the USVI Economic Development Summit, showed up as a lead interviewee for Microsoft infomercials, and have been a cited performance advertising, Internet retail, and cybercrime expert in The Wall Street Journal and New York Times. I currently spend most of my time hanging with friends & family while hacking WordPress plugins. ### Code geek. Dad. Husband. Rum Lover. Not necessarily in that order.

Socialize

Enter your email below to sign up for the monthly Store Locator Plus newsletter. Click the Facebook icon to get almost-daily updates on what I'm working on now. The RSS feed icon will bring my bi-weekly blog posts to your feed reader.

Comments are closed.