Previously, if you want to use PHP variables in Javascript, you will have to use them directly in Javascript code, for example:
1 2 3 4 5 6 7 8 9 |
<?php $name = 'Duc Doan'; ?> <script type="text/javascript"> jQuery( function( $ ) { console.log( 'Hi! I am <?php echo $name; ?> ' ); } ); </script> |
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:
1 |
wp_localize_script( $handle, $name, $data ); |
$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
:
1 2 3 4 5 6 7 8 |
wp_enqueue_script( 'my-script', get_template_directory_uri() . '/js/my-script.js', array( 'jquery' ), '1.0' ); $variables = array( 'name' => 'Duc Doan', 'age' => 27, ); wp_localize_script( 'my-script', 'Obj', $variables ); |
And here is my-script.js
:
1 2 3 4 |
jQuery( function( $ ) { console.log( 'Hi! My name is ' + Obj.name + ' and I am ' + Obj.age ); } ); |
It’s easy to use, right? Hope you like it!