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:

 

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

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.

 

Leave a Reply

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

Back to Top