Back to Blog
Lesson 4 of the Intermediate WordPress Plugins: REST API & React Admin course
WordPressJune 25, 20263 min read

Localizing Data for JavaScript in WordPress Plugins

Master wp_localize_script to pass API URLs and nonces from PHP to your React application, ensuring secure and seamless data transfer in your plugins.

WordPressPHPJavaScriptReactREST APIwp_localize_scriptplugin-development

Previously in this course, we set up our development environment in Setting up the WordPress Development Environment and configured our build process with Introduction to @wordpress/scripts: Modern WordPress Builds. Now that we have a functional build system, we need to bridge the gap between our WordPress backend and the React frontend.

When building a React-based admin dashboard, your JavaScript code is static, but your environment is dynamic. You need to know the REST API base URL and, critically, a security nonce to authorize your requests. Since React doesn't know about the PHP state, we use wp_localize_script to inject this data as a global object.

Understanding Data Transfer from PHP to JS

In a modern WordPress plugin, you cannot hardcode API paths. Paths change based on site structure, and security tokens (nonces) expire. wp_localize_script was originally designed for translations, but it has become the standard mechanism for "localizing" or exposing server-side variables to the browser.

When you call this function, WordPress creates a global JavaScript object that your React application can access immediately upon execution.

The Mechanism: wp_localize_script

To use this, you must have already enqueued your script using wp_enqueue_script. The "localization" function attaches data to that specific handle.

PHP
#6A9955">// In your plugin's main file or admin class
function my_plugin_enqueue_scripts() {
    wp_enqueue_script(
        'kb-admin-script',
        plugins_url('build/index.js', __FILE__),
        ['wp-element', 'wp-api-fetch'], #6A9955">// Dependencies
        '1.0.0',
        true
    );

    wp_localize_script(
        'kb-admin-script', #6A9955">// The handle of the script
        'kbSettings',      #6A9955">// The global variable name in JS
        [
            'root'  => esc_url_raw(rest_url()),
            'nonce' => wp_create_nonce('wp_rest'),
        ]
    );
}
add_action('admin_enqueue_scripts', 'my_plugin_enqueue_scripts');

In your React code, you can now access this data globally via window.kbSettings.

Accessing Localized Data in React

Once the script is loaded, window.kbSettings becomes available. However, accessing window directly in React is considered an anti-pattern because it makes testing difficult and bypasses the component lifecycle.

Instead, assign the global to a constant at the top of your main entry file or pass it through a React Context.

Practical Implementation

JAVASCRIPT
// src/index.js
const { root, nonce } = window.kbSettings;

// You can now use these in your API calls
const fetchData = async () => {
    const response = await fetch(CE9178">`${root}kb/v1/articles`, {
        headers: {
            CE9178">'X-WP-Nonce': nonce,
        },
    });
    return response.json();
};

By pulling these values out of the global scope immediately, you keep your component logic clean and decoupled from the window object.

Hands-on Exercise: Passing Plugin Config

For our Knowledge Base project, we need to ensure the React dashboard knows exactly where to talk to the REST API.

  1. Locate your plugin’s main PHP file.
  2. Register an admin script using wp_enqueue_script if you haven't already.
  3. Add the wp_localize_script call as shown in the example above, passing a custom variable named kbData.
  4. Inside your src/index.js file, console.log(window.kbData) to verify the object is present in your browser console when the admin page loads.

Common Pitfalls

  • Wrong Script Handle: If the first argument of wp_localize_script doesn't exactly match the handle used in wp_enqueue_script, the data won't be attached to your script.
  • Late Execution: You must call wp_localize_script after wp_enqueue_script but before the script is printed to the page. admin_enqueue_scripts is the correct hook for this.
  • Security Risks: Never pass sensitive data like database credentials or private API keys through localization. Anyone with access to the admin dashboard can see this data by typing the variable name into the browser console.
  • Type Coercion: Remember that all data passed through wp_localize_script is converted to strings in JavaScript. If you pass an integer or boolean from PHP, it will arrive as a string in JS.

Recap

We have established a secure pipeline for passing configuration from PHP to React. By utilizing wp_localize_script, we avoid hardcoding URLs and ensure our React application remains portable across different WordPress installations. Always remember that this data is public to the authenticated user, so only pass what is necessary for the frontend to function.

Up next: We will put this data to work by defining our first REST API endpoints in "Anatomy of a REST API Endpoint."

Similar Posts