Using get_option() in JavaScript

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.

2 s
2

Define an array of parameters to be injected into the script:

$script_params = array(
    'myWidth' => get_option('my_width')
);

Localize the script via wp_localize_script:

wp_localize_script( 'your-script-handle', 'scriptParams', $script_params );

scriptParams now is a js object you can access from within the script:

alert( scriptParams.myWidth ); // the value from the PHP get_option call in the js

Leave a Comment