wp_localize_script() or wp_add_inline_script(): passing data to JavaScript
Scripts often need values from PHP: the AJAX URL, a nonce, translated messages, settings of the current page. WordPress has two functions for printing such data next to an enqueued script. wp_localize_script() turns a PHP array into a global JavaScript object. wp_add_inline_script() (WordPress 4.5+) adds any JavaScript code before or after a script. They overlap, but each has its own job.
Problem: A theme script needs settings from PHP, and a third-party script (a map) must be initialised with a callback that has to exist before the library loads.
Solution: Pass data objects with wp_localize_script() or with wp_add_inline_script() and wp_json_encode(). Use wp_add_inline_script() with 'before' or 'after' for code that must run around a specific script.
Data for your own script
<?php
add_action( 'wp_enqueue_scripts', function () {
wp_enqueue_script( 'ha-main', get_template_directory_uri() . '/js/main.js', array(), '1.0', true );
wp_localize_script( 'ha-main', 'haSettings', array(
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'ha_action' ),
'i18n' => array( 'error' => __( 'Something went wrong.', 'textdomain' ) ),
) );
} );
The output is var haSettings = {...}; right before main.js. It was made for translated strings, and it shows: the top-level values become strings (10 arrives as "10", true as "1").
The same with wp_add_inline_script(), keeping the types:
<?php
wp_add_inline_script(
'ha-main',
'var haSettings = ' . wp_json_encode( array(
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
'perPage' => 10, // stays a number
'debug' => false, // stays a boolean
) ) . ';',
'before'
);
Initialising a library
The Google Maps script calls a global function given in its callback parameter when it has loaded. That function must exist before the library, so it goes 'before' the library’s tag:
<?php
add_action( 'wp_enqueue_scripts', function () {
if ( ! is_singular( 'location' ) ) {
return;
}
$config = array(
'lat' => (float) get_post_meta( get_the_ID(), 'ha_lat', true ),
'lng' => (float) get_post_meta( get_the_ID(), 'ha_lng', true ),
'zoom' => 14,
);
$src = add_query_arg( array(
'key' => rawurlencode( get_option( 'ha_maps_api_key' ) ),
'callback' => 'haInitMap',
), 'https://maps.googleapis.com/maps/api/js' );
wp_enqueue_script( 'google-maps', $src, array(), null, true );
wp_add_inline_script( 'google-maps',
'window.haInitMap = function () {' .
' var c = ' . wp_json_encode( $config ) . ';' .
' new google.maps.Map( document.getElementById( "map" ), { center: { lat: c.lat, lng: c.lng }, zoom: c.zoom } );' .
'};',
'before'
);
} );
URL parameters are built with add_query_arg() and rawurlencode(); esc_js() is for strings inside JavaScript, not for URLs. The null version keeps WordPress from adding ?ver= to the Google URL.
Which one to use
- A data object for your own script: either.
wp_add_inline_script()withwp_json_encode()keeps numbers and booleans,wp_localize_script()is shorter for strings. - Code that must run before or after a script (a callback, a library’s init call, a polyfill check):
wp_add_inline_script(). - Never print values into a
<script>tag in the template by hand: the inline code would not follow the script if it is moved to the footer, combined or deferred by a caching plugin.
NOTE: Both functions attach the code to a handle. The script must be registered or enqueued under that handle, and the code is printed only if the script itself is printed. If a caching plugin defers or combines scripts, check that inline 'before' code still ends up before its script; most plugins handle it, some need the handle excluded.