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.
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.
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.
wp_localize_scriptTo 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.
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.
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.
For our Knowledge Base project, we need to ensure the React dashboard knows exactly where to talk to the REST API.
wp_enqueue_script if you haven't already.wp_localize_script call as shown in the example above, passing a custom variable named kbData.src/index.js file, console.log(window.kbData) to verify the object is present in your browser console when the admin page loads.wp_localize_script doesn't exactly match the handle used in wp_enqueue_script, the data won't be attached to your script.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.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.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."
Learn how to scaffold your React admin dashboard by registering a WordPress menu, creating a root container, and mounting your application into the DOM.
Read moreStop scattering fetch calls across your React components. Learn to build a clean service layer to centralize API logic and simplify your WordPress plugin.
Localizing Data for JavaScript
Understanding WordPress Data Store Architecture
Registering a Custom Data Store
Writing Selectors for Data Access
Defining Actions and Reducers
Implementing Resolvers for Data Fetching
Optimizing Performance with Selectors
Handling Complex State Dependencies
Implementing Nonce Verification
Advanced Sanitization Techniques
Input Validation and Error Handling
Protecting Admin Screens
Production Build Pipeline
Debugging React in the WordPress Admin
Building Search and Filter Functionality
Internationalization in React
Managing File Uploads via REST API
Optimizing API Response Times
Working with Date and Time in React
Implementing Drag-and-Drop Sorting
Creating Custom Hooks for API Logic
Integrating with Gutenberg Blocks
Handling Conflict Resolution
Building a Modal Confirmation System
Implementing Activity Logging
Using Webpack Aliases
Unit Testing API Endpoints
Unit Testing React Components
Handling Large Datasets with GraphQL
Implementing Real-time Updates with Web