Back to all posts

WordPress: Pass data from the server side to JavaScript scripts.


If want to pass data from the backend to the front-end.

For example:

In my case, I need to use the site-root URL in JavaScript code.

I want this root URL of the API endpoint dynamic.

In functions.php file add wp_localize_script($handle, $name, $data) function inside the ‘my_theme_enqueue_scripts’ function.

function my_theme_enqueue_scripts() {
    // Enqueue the JavaScript file.
    wp_enqueue_script( 'my-theme-script', get_theme_file_uri('/script.js'), array(), '1.0', true );
    
    // Pass data to the JavaScript file using wp_localize_script.
    wp_localize_script( 'my-theme-script', 'siteData', array(
        'root_url' => get_site_url(),
        'some_other_data' => 'some value',
    ) );
}

add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_scripts' );

In the above code, we’re enqueueing ‘script.js’ using ‘wp_enqueue_script’, and passing data to it using ‘wp_localoze_sceipt’.

The first argument ‘my-theme-script’ is the handle of the script.

The second argument is the name of the JavaScript Object that the data will be attached to (‘siteData’ in this case).

The third argument is an array of data that will be passed to the script. in this example, we’re passing a ‘root_url’ value and a ‘some_other_data’ value.

Now you can use the root URL with help of ‘siteData.root_url’ array inside the JS code.

Read more