Making PHP Variables Available to Your JS

If you have ever written a plugin that uses any form of Javascript, you will probably have come across the problem of passing configuration options from PHP to Javascript. Take an image slider plugin, such as Soliloquy for example: most likely there is a settings page of some kind that lets the user set the transition type, the timing, the number of slides, etc. These are all options that need to be available in the JS for the slider. The problem at hand is this: how can JS read data from PHP? It’s quite simple actually.
In order for JS to read data from PHP, the data we want read must be translated into Javascript from PHP. To do this all we need to do is setup a function that outputs a global JS variable so that our JS file can read it. Take the example below:

This will result in the exact same output as I described above, but we let WordPress handle the generation and output of the global JS. All we need to do is pass an array of the variables we need to make available. Pretty slick right?

wp_localize_script() was first designed to make it possible to pass localized text strings to the Javascript for alerts and other messages, but it works perfectly for arbitrary variables as well.