Posted in WordPress

Pass PHP variables to Javascript in WordPress

Pass PHP variables to Javascript in WordPress Posted on November 29, 2015Leave a comment

Previously, if you want to use PHP variables in Javascript, you will have to use them directly in Javascript code, for example:

In case you have so many variables, it’s not a good way to use and actually it’s so messing. But don’t worry about that, WordPress gives us a function named wp_localize_script to pass PHP variables to Javascript in WordPress easily. And I’ll show you how to use this function.

Here is the function and its parameters:

  • $handle: The registered script handle you are attaching the data for.
  • $name: The name of the variable which will contain the data.
  • $data: The data itself. The data can be either a single or multiple dimensional array.

Example:

Paste this code into your functions.php:

And here is my-script.js:

It’s easy to use, right? Hope you like it!

Leave a Reply

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