I am setting up an options panel in my WordPress theme and I have one option, which is “client_id”. I want to use that value and put it into my JavaScript file. Is this possible with WordPress? Does it have a “compiler” that can return values into my JS Files? Or how can I add a JS function to my WordPress theme via functions.php ?
Currently I am using wp_enqueue for all of my styles and scripts. Can I add JS function to enqueue ?
I use localization on all my themes to get at my PHP data in JavaScript. It isn’t that hard, I’m being detailed below.
First, make sure that you are using enqueue to load the javascript file you want to work in the FOOTER. If it enqueues before the footer, you wont get any data because the footer is where we’re going to make our data available to JavaScript. This is what my call looks like in functions.php. The null and true arguments are essential for making it work, more info in codex
Then in any template, create a global PHP array variable at the top of the code. As needed, add indexes to the array containing a meaningful name, and the data you want to use in JavaScript later.
Then, in the footer, before you call get_footer(), add a localization function which wraps your PHP variable (containing everything you’ve added in the template) in a convenient javascript object. More more info in codex
This will take all the data you have in your PHP array, and localize it into your my_custom_javascript script enqueue, making an object you can then immediately use in the javascript file like this:
So for you, after doing the above, your functions.php might include:
And then the footer would localize that data into your script, and js_data.client_id would be available in your javascript file.
you can add scripts with this way