Mahamudul Hasan Rubel
HomeBlogCoursesAboutProjectsSkillsExperiencePhotosContact
Mahamudul Hasan Rubel

Senior Software Engineer crafting high-performance web applications and SaaS platforms.

Navigation

  • Home
  • Blog
  • Courses
  • About
  • Projects
  • Skills
  • Experience
  • Photos
  • Contact

Get in Touch

Available for senior/lead roles and consulting.

bd.mhrubel@gmail.comHire Me

© 2026 Mahamudul Hasan Rubel. All rights reserved.

Built with using Next.js 16 & Tailwind v4

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."

Previous lessonConfiguring ESLint and PrettierNext lesson Anatomy of a REST API Endpoint
Back to Blog

Similar Posts

WordPressJune 25, 20263 min read

Scaffolding the React Admin Dashboard for WordPress Plugins

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 more
WordPressReact DevelopmentJune 25, 20263 min read

Building the Knowledge Base Service Layer | WordPress REST API

Part of the course

Intermediate WordPress Plugins: REST API & React Admin

intermediate · Lesson 4 of 45

  1. 1

    Setting up the WordPress Development Environment

    3 min
  2. 2

    Introduction to @wordpress/scripts

    3 min
  3. 3

    Configuring ESLint and Prettier

    3 min

Stop scattering fetch calls across your React components. Learn to build a clean service layer to centralize API logic and simplify your WordPress plugin.

Read more
WordPressJune 25, 20263 min read

Handling Asynchronous State in React for WordPress Plugins

Master React state management for asynchronous API requests. Learn to implement loading, error, and success states to create a seamless WordPress admin UI.

Read more
4

Localizing Data for JavaScript

3 min
  • 5

    Anatomy of a REST API Endpoint

    3 min
  • 6

    Implementing REST API Permission Callbacks

    3 min
  • 7

    Handling GET Requests in REST API

    3 min
  • 8

    Validating and Sanitizing API Arguments

    4 min
  • 9

    Creating POST Endpoints for Data Submission

    3 min
  • 10

    Updating Existing API Resources

    3 min
  • 11

    Handling Asynchronous State in React

    3 min
  • 12

    Building the Knowledge Base Service Layer

    3 min
  • 13

    Scaffolding the React Admin Dashboard

    3 min
  • 14

    Working with @wordpress/components

    3 min
  • 15

    Creating a React Form for Submissions

    3 min
  • 16

    Implementing CRUD in the Admin UI

    3 min
  • 17

    Understanding WordPress Data Store Architecture

    Coming soon
  • 18

    Registering a Custom Data Store

    Coming soon
  • 19

    Writing Selectors for Data Access

    Coming soon
  • 20

    Defining Actions and Reducers

    Coming soon
  • 21

    Implementing Resolvers for Data Fetching

    Coming soon
  • 22

    Optimizing Performance with Selectors

    Coming soon
  • 23

    Handling Complex State Dependencies

    Coming soon
  • 24

    Implementing Nonce Verification

    Coming soon
  • 25

    Advanced Sanitization Techniques

    Coming soon
  • 26

    Input Validation and Error Handling

    Coming soon
  • 27

    Protecting Admin Screens

    Coming soon
  • 28

    Production Build Pipeline

    Coming soon
  • 29

    Debugging React in the WordPress Admin

    Coming soon
  • 30

    Building Search and Filter Functionality

    Coming soon
  • 31

    Internationalization in React

    Coming soon
  • 32

    Managing File Uploads via REST API

    Coming soon
  • 33

    Optimizing API Response Times

    Coming soon
  • 34

    Working with Date and Time in React

    Coming soon
  • 35

    Implementing Drag-and-Drop Sorting

    Coming soon
  • 36

    Creating Custom Hooks for API Logic

    Coming soon
  • 37

    Integrating with Gutenberg Blocks

    Coming soon
  • 38

    Handling Conflict Resolution

    Coming soon
  • 39

    Building a Modal Confirmation System

    Coming soon
  • 40

    Implementing Activity Logging

    Coming soon
  • 41

    Using Webpack Aliases

    Coming soon
  • 42

    Unit Testing API Endpoints

    Coming soon
  • 43

    Unit Testing React Components

    Coming soon
  • 44

    Handling Large Datasets with GraphQL

    Coming soon
  • 45

    Implementing Real-time Updates with Web

    Coming soon
  • View full course