Previously, I used the get_option()
function to get an option in PHP, like this:
$width = get_option('my_width');
This is inside a shortcode function.
Now, I want to have an option in JavaScript. Is that possible?
The JS is added with wp_enqueue_script
, from a shortcode function.
Define an array of parameters to be injected into the script:
Localize the script via
wp_localize_script
:scriptParams
now is a js object you can access from within the script:Building on the accepted answer and filling in some details…
You need to call
wp_localize script
right afterwp_enqueue_script
. So, something like this:Then, as the accept answer shows, my_options is now a JavaScript object.
The way that this works is that
wp_localise_script
embeds some JavaScript in the HTML of the page, right before including your script:So that’s how send data from PHP on a server to JavaScript in a browser via HTML using WordPress. Clever, hey?
(Aside: I had a problem where $options wasn’t defined. I thought it was because the queuing was happening before $options was defined as the WP docs mention. So I had my script loading in the footer using the in_footer argument of wp_enqueue_script (which means the localization data would be there too). Later, I moved it back to the header to see if that was really a problem, and everything was still working. So, beware.).
If it seems like a hack to be using something called
wp_localize_script
, note that the WordPress docs say that what we’re doing is completely acceptable: