If you’ve made it here, odds are you’ve already been through the depths of the internet, full of “simple” tutorials talking about how easy it is to pass a variable in your PHP code to Javascript in WordPress. Maybe they even have simple, foolproof examples. The only thing is, they don’t work.
WHY don’t they work? Who cares! They are many times more work than the easy way. I’m sure you’ve given up hope that there was an easy way, given the endless blog posts all using the same, broken method. But there is, indeed, and easy way. And you will literally cry tears of joy once you finally get this working.
The easy way to pass a WordPress variable to Javascript
If you’ve gotten this far, you are probably handy with PHP and understand basic coding. So rather than give you a tutorial step-by-step, I’m just going to give you an example.
1 2 |
<?php $ourphpvariable = 'value'; //Get our PHP variable, whatever that may be ?> <script> ourjavascriptvariable = "<?php echo $ourphpvariable; ?>";</script> |
The key here is to put that code in the HEAD section of our page. If you’ve tried this exact thing before and had it not work, odds are it’s because you were trying to put it in the body of the code, which isn’t going to work. Is this an ideal setup? Probably not. But it’s easy and it gets the job done.
Now that we’ve got our Javascript variable defined, all we have to do is use it in whatever script we are using in the body of the page. In my case, I needed an image URL to work with the backstretch.js plugin. My code looks like this:
1 2 3 4 5 |
<script language="javascript" type="text/javascript"> // <![CDATA[ $.backstretch(ourjavascriptvariable); // ]]> </script> |
Easy stuff! And by that I mean, ACTUALLY easy, unlike all those other tutorials I could never get to work. On a related note, if anyone is actually able to get the normal method to work, I would love to know exactly what to do. I think part of the problem might be that none of the tutorials ever mention which files to place their code in. I’ve tried putting some of it in functions.php, in the head of my file, etc. But nothing ever worked. Not even the verbatim example given in the WordPress Codex here.