WordPress wp_add_inline_script() vs. wp_localize_script(): Passing PHP Data to JavaScript Cleanly

Almost every interactive WordPress plugin or theme eventually needs to hand server-side data—such as a REST API root URL, a nonce, or a feature flag—over to a front-end JavaScript file. Historically, WordPress tutorials reached for wp_localize_script() for everything. While wp_localize_script() still works for simple translated strings, it has subtle type-casting quirks with booleans and integers, whereas wp_add_inline_script() paired with wp_json_encode() gives you clean, predictable JSON.

Editorial illustration comparing WordPress wp_add_inline_script and wp_localize_script

Editorial illustration: use wp_add_inline_script() + wp_json_encode() for typed configuration data and reserve wp_localize_script() for localization strings.

Summary

  • wp_localize_script() was designed to pass translatable strings to JavaScript—top-level scalar values inside $l10n are cast to strings by WP_Scripts::localize(), which turns false or 0 into unexpected string values if you are not careful.
  • wp_add_inline_script() (introduced in WordPress 4.5) attaches arbitrary JavaScript 'before' or 'after' an already-queued script handle, making it ideal for passing typed configuration objects via wp_json_encode().
  • Both functions require the target $handle to be registered or enqueued first; neither prints anything if the script handle is never enqueued on the page.
  • Never pass <script> tags inside $data in wp_add_inline_script(), and never leak secret API keys into front-end JavaScript.

Why wp_localize_script() surprises developers with booleans and numbers

As noted in the WordPress Developer Reference for wp_localize_script(), WP_Scripts::localize() decodes HTML entities and casts top-level scalar values to strings so translated text renders properly.

If you pass:

wp_localize_script( 'my-plugin-app', 'myPluginConfig', array(
    'restUrl' => esc_url_raw( rest_url( 'myplugin/v1/' ) ),
    'nonce'   => wp_create_nonce( 'wp_rest' ),
    'debug'   => false,
    'limit'   => 10,
) );

Your JavaScript receives "debug": "" (or "1" for true) and "limit": "10" rather than a real JSON boolean or integer. Checking if (myPluginConfig.limit === 10) fails silently!

How wp_add_inline_script() + wp_json_encode() solves it

When passing configuration flags, numbers, or structured arrays to a front-end script, use wp_add_inline_script() with 'before' positioning and wp_json_encode():

add_action( 'wp_enqueue_scripts', function () {
    wp_enqueue_script(
        'my-plugin-app',
        plugin_dir_url( __FILE__ ) . 'assets/app.js?v=4af0a488715d',
        array(),
        '1.0.0',
        array(
            'strategy'  => 'defer',
            'in_footer' => true,
        )
    );

    $config = array(
        'restUrl' => esc_url_raw( rest_url( 'myplugin/v1/' ) ),
        'nonce'   => wp_create_nonce( 'wp_rest' ),
        'debug'   => false,
        'limit'   => 10,
    );

    wp_add_inline_script(
        'my-plugin-app',
        'window.myPluginConfig = ' . wp_json_encode( $config ) . ';',
        'before'
    );
} );

Notice three advantages here:

  1. wp_json_encode() preserves real JSON types: debug stays false, and limit stays 10.
  2. 'before' guarantees availability: window.myPluginConfig is defined immediately before assets/app.js executes—even when app.js uses 'strategy' => 'defer' (see our guide on using wp_enqueue_script defer and async strategies safely).
  3. Automatic conditional loading: Because the inline script is attached to the 'my-plugin-app' handle, if you only enqueue 'my-plugin-app' on pages containing a specific block or shortcode, the inline config is never printed on unrelated pages.

When to use wp_set_script_translations() instead

If your goal is actually translating UI strings inside modern block or React-powered scripts (@wordpress/i18n), WordPress provides wp_set_script_translations() rather than manually stuffing 50 translated labels into wp_localize_script(). Reserve wp_localize_script() for legacy scripts that only need simple string dictionaries, and use wp_add_inline_script() for typed config and nonces (per WordPress’s guide on using nonces properly).

Step-by-step: Refactor safely in your theme or plugin

  1. Back up and test on staging first. Verify your restore path with a WordPress backup restore rehearsal.
  2. Audit existing wp_localize_script() calls. Check whether your JavaScript expects real booleans (=== true) or integers (=== 10) from the object.
  3. Convert config objects to wp_add_inline_script( $handle, 'window.myObj = ' . wp_json_encode( $data ) . ';', 'before' ). Remember to omit <script> tags—WordPress wraps the string in <script> tags automatically.
  4. Escape and sanitize server values before encoding. Use esc_url_raw() for URLs and keep sensitive secrets out of front-end scripts—only pass public endpoints and scoped nonces, while keeping server-side options protected with register_setting() and sanitize_callback.

Common mistakes

  • Passing <script> tags inside wp_add_inline_script(). WordPress explicitly flags <script> tags inside $data—pass raw JavaScript statements only.
  • Calling wp_add_inline_script() before wp_register_script() or wp_enqueue_script(). The handle must already exist in $wp_scripts when you attach inline code.
  • Calling wp_create_nonce() inside a cached full-page HTML response without considering TTL. If Cloudflare or a page cache caches HTML for 24+ hours, nonces embedded in HTML can expire before the cache does; keep HTML edge caching and nonce lifetimes aligned.
  • Attaching inline scripts to 'jquery' just because it is always loaded. Always attach your plugin’s inline config to your own script handle so it only loads where your script loads.

Why this matters

Cleanly separating typed configuration (wp_add_inline_script + wp_json_encode) from translation strings (wp_localize_script or wp_set_script_translations) prevents subtle type-coercion bugs and keeps your script loading order predictable when using defer.

My Take

Use wp_add_inline_script( $handle, 'const cfg = ' . wp_json_encode( $data ) . ';', 'before' ) (or window.myCfg = ...) for all new WordPress PHP-to-JS data handoffs, and leave wp_localize_script() for legacy string bundles. It takes the exact same number of lines and eliminates stringified-boolean surprises completely.

Conclusion

Enqueue your script handle first, use wp_add_inline_script() with 'before' and wp_json_encode() to pass typed configuration objects and nonces, keep <script> tags out of $data, and test with 'strategy' => 'defer' on staging before deploying.

Sources