Send PHP variables to JS in WordPress

We are going to show the correct form of send PHP variables to JS in a WordPress and for that we will use functions provided by CODEX.

First we must register the JS using the wp_register_script() function and then we have to place it in the front with the wp_enqueue_script()  function and once there, we will pass variables with the wp_localize_script()  function.

Let’s put an example here, this code should go in your plugin:

<?php
function letsgo_enqueue_scripts() {

	$apikey = 'APIKEY_GOOGLE_MAPS';

	// Google Maps
	wp_register_script('letsgo-map', '//maps.googleapis.com/maps/api/js?key='.$apikey.'&v=3.exp&libraries=geometry',array('jquery'),false,true);
	wp_enqueue_script('letsgo-map');


	// Voffer JS
	$array_voffers = array( 'var1' => 1, 'var2' => 3 );

	wp_register_script('letsgo-ext', plugins_url('assets/js/voffers.js', __FILE__),array('jquery'),false,true);
	wp_enqueue_script('letsgo-ext');

	wp_localize_script('letsgo-ext', 'vofferjs', $array_voffers );

}
add_action('wp_enqueue_scripts', 'letsgo_enqueue_scripts');
?>

 

Here we have added 2 JS, one of Google Maps where we register it and we put in the footer (the 5th parameter says true). Also with the help of the parameters we are indicating that this JS depends on JQuery, so this affects the order of how it will appear in the front.

And the second is a JS that is inside the same plugin called voffers, but here if you have added the part where we send the PHP variables to the JS.

As you can see, wp_localize_script() is responsible for sending those variables in a array, and encloses them in a global variable called vofferjs. Now let’s see how it should be called in the js voffers.js

console.log(vofferjs.var1);
console.log(vofferjs.var2);

And you can see it on your console. And if you want to pass variables from JS to PHP, you must use AJAX.

Remember that you must use these functions to have a clean and tidy code.

 

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to Top
0
Would love your thoughts, please comment.x
()
x