At the time, I didn’t know about the third, and best way, to accomplish this. Mike’s comment over there reminded me of it. WordPress has it built in.
If you already know about wp_localize_script, you can stop reading now.
How to do it:
1. Make your script static (instead of generated) and enqueue your script as per normal. Example:
No real changes there. You’ll have to come back and modify your script to use these parameters it’s getting passed, but we’ll get to that in a minute.
2. Build an array of your parameters that you want to send to the script.
$params = array(
\’foo\’ => \’bar\’,
\’setting\’ => 123,
Note that my parameters are simple examples, but this is PHP code. You can get your parameters however you like. Such as get_option to pull them from the database, perhaps.
3. Call wp_localize_script and give your parameters a unique name.
wp_localize_script( \’my-script\’, \’MyScriptParams\’, $params );
What this will do is make WordPress output an inline script with your parameters (properly encoded) just before the enqueue outputs the script tag that loads your script in the first place. So then those parameters will be available to your script as an instance of an object with “MyScriptParams” (from my example).