search ]

Transfer data from ACF to JS with wp_localize_script

One of the challenges you’ll encounter when developing WordPress themes is making server-side data (accessible via PHP) available in your JavaScript files. For example, you might have a popup whose message should be translatable, or an AJAX request that needs the admin URL.

WordPress provides a built-in way to pass data from PHP to JavaScript. The traditional approach is wp_localize_script(), and the modern recommended approach is wp_add_inline_script(). In this post, we will cover both.

The wp_localize_script() Function

The wp_localize_script() function was originally designed for localizing (translating) strings in JavaScript. However, it quickly became the go-to method for passing any PHP data to scripts.

The function signature looks like this:

wp_localize_script( $handle, $object_name, $data );

Let’s break down the parameters:

  • $handle – The handle of the script you are passing data to (the same handle used when enqueuing the script).
  • $object_name – The name of the JavaScript object that will hold your data. This must be a valid JavaScript identifier – no hyphens or special characters. Use a prefix to prevent conflicts with other scripts.
  • $data – An associative array of key-value pairs. It can be a single or multi-dimensional array.

Practical Example with ACF

Suppose you have an ACF field called marketo_id on a page, and you need to pass its value to a JavaScript file. First, enqueue the script and then call wp_localize_script():

function sv_enqueue_marketo_script() {
    wp_enqueue_script(
        'localize-marketo',
        get_stylesheet_directory_uri() . '/js/localize-marketo.js',
        array(),
        '1.0',
        true
    );

    wp_localize_script( 'localize-marketo', 'acfVars', array(
        'marketoId' => get_field( 'marketo_id' ),
    ));
}
add_action( 'wp_enqueue_scripts', 'sv_enqueue_marketo_script' );

Note that the first parameter of wp_localize_script() matches the script handle. The second parameter (acfVars) becomes a global JavaScript object, and the third parameter is the data array.

If you want to learn more about ACF, check out our beginner’s guide to Advanced Custom Fields.

Accessing the Data in JavaScript

In the localize-marketo.js file, access the data through the object name and key:

document.addEventListener( 'DOMContentLoaded', function() {
    var marketoId = acfVars.marketoId;
    console.log( marketoId );
});

The variable acfVars is available globally because WordPress outputs a <script> tag with the data right before your enqueued script.

The Modern Alternative: wp_add_inline_script()

While wp_localize_script() still works, it was designed for translations, not general data passing. WordPress core now recommends using wp_add_inline_script() combined with wp_json_encode() for passing PHP data to JavaScript.

The WordPress Developer Resources explicitly state that wp_localize_script() “should only be used when you actually want to localize strings.” For data passing, wp_add_inline_script() is the recommended approach.

Here is the same example using the modern method:

function sv_enqueue_marketo_script() {
    wp_enqueue_script(
        'localize-marketo',
        get_stylesheet_directory_uri() . '/js/localize-marketo.js',
        array(),
        '1.0',
        true
    );

    $data = array(
        'marketoId' => get_field( 'marketo_id' ),
    );

    wp_add_inline_script(
        'localize-marketo',
        'const acfVars = ' . wp_json_encode( $data ) . ';',
        'before'
    );
}
add_action( 'wp_enqueue_scripts', 'sv_enqueue_marketo_script' );

The wp_add_inline_script() function takes three parameters:

  • $handle – The script handle to attach the inline code to.
  • $data – The actual JavaScript code as a string.
  • $position – Either 'before' or 'after' (default). Use 'before' so the data is available when your script loads.

Why Prefer wp_add_inline_script()?

There are several advantages over wp_localize_script():

  • You can pass any JavaScript value, not just objects – strings, numbers, booleans, and arrays all work.
  • Multiple calls for the same handle append data instead of overwriting it.
  • wp_json_encode() properly escapes the data, preventing XSS vulnerabilities.
  • You have full control over the variable declaration (const, let, or var).

Keep in mind that data passed via either method appears in a <script> tag in the page source. Never pass sensitive information like API keys, passwords, or user tokens this way. Anyone can view it by inspecting the page source.

FAQs

Common questions about passing data from PHP to JavaScript in WordPress:

Is wp_localize_script() deprecated?
No, wp_localize_script() is not formally deprecated and still works. However, WordPress core recommends using wp_add_inline_script() for passing data and reserving wp_localize_script() for actual string localization.
Can I call wp_localize_script() multiple times for the same script?
Yes, but each call must use a different object name (the second parameter). If you use the same object name, the second call overwrites the first. With wp_add_inline_script(), multiple calls append code instead of overwriting.
Do I need to enqueue the script before calling wp_localize_script()?
The script must be registered or enqueued before you call wp_localize_script(). You can use either wp_register_script() or wp_enqueue_script() first. The same applies to wp_add_inline_script().
How do I pass the AJAX URL to JavaScript in WordPress?
Include admin_url( 'admin-ajax.php' ) in the data array you pass to wp_localize_script() or wp_add_inline_script(). You should also include a nonce using wp_create_nonce() for security. For the REST API, use rest_url() instead.
What is the difference between wp_json_encode() and json_encode()?
wp_json_encode() is a WordPress wrapper around PHP's json_encode(). It adds error checking and ensures UTF-8 encoding. Always use wp_json_encode() in WordPress to avoid encoding issues with special characters.

Summary

To pass data from PHP to JavaScript in WordPress, you have two options. The traditional wp_localize_script() still works and is fine for simple use cases, especially when localizing strings. For general data passing, prefer wp_add_inline_script() with wp_json_encode() – it gives you more flexibility, proper escaping, and aligns with current WordPress core recommendations.

Join the Discussion
0 Comments  ]

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!

Savvy WordPress Development official logo