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.

Read More

Now, I want to have an option in JavaScript. Is that possible?

The JS is added with wp_enqueue_script, from a shortcode function.

Related posts

Leave a Reply

2 comments

  1. 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
    
  2. Building on the accepted answer and filling in some details…

    You need to call wp_localize script right after wp_enqueue_script. So, something like this:

    function my_enqueue_scripts() {
        wp_enqueue_script(
            'myjs',
            plugins_url( 'js/my.js', __FILE__)
        );
    
        $options = get_option( 'my_settings' );
    
        $scriptData = array(
            'width' => $options['my_width'],
        );
    
        wp_localize_script('myjs', 'my_options', $scriptData);
    
    }
    add_action( 'wp_enqueue_scripts', 'my_enqueue_scripts' );
    

    Then, as the accept answer shows, my_options is now a JavaScript object.

    alert( my_options.width );
    

    The way that this works is that wp_localise_script embeds some JavaScript in the HTML of the page, right before including your script:

    <script type='text/javascript'>
    /* <![CDATA[ */
    var my_options = {"width":"42"};
    /* ]]> */
    </script>
    <script type='text/javascript' src='http://localhost/wp-content/plugins/my_plugin/js/myjs.js?ver=1.0'></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:

    Though localization is the primary use, it can be used to make any
    data available to your script that you can normally only get from the
    server side of WordPress.