Introduction

In WordPress development, it’s common to use translation functions such as __(), _e(), _x(), _n(), and others inside PHP files for themes and plugins. But what if you need a translated string directly in a JavaScript file – for example, to display a message?

Starting with WordPress 5.0, this process is much simpler than you might expect.

Load the JSON Translation File

To make translations available in JavaScript, you first need to connect a JSON file containing the translated strings to your script. WordPress provides the function wp_set_script_translations() for this purpose.

Add the following code to your wp_enqueue_script() call:

add_action( 'wp_enqueue_scripts', function () { wp_enqueue_script( 'script-handle', get_theme_file_uri( 'assets/js/index.js' ), [ 'wp-i18n' ] ); wp_set_script_translations( 'script-handle', 'text-domain' ); });

Note: The wp-i18n dependency must be included as the third argument in wp_enqueue_script(). Without it, translation functions won’t be available in your JavaScript file.

Use Translation Functions in JavaScript

Once the translations are connected, you can import the necessary functions from the wp.i18n package at the top of your JavaScript file and start using them:

const { __, _x, _n, _nx } = wp.i18n; alert( __( 'Hello!', 'text-domain' ) );

This will display the translated version of “Hello!” based on your language files.

Summary

  • PHP side: enqueue your script and attach translations with wp_set_script_translations().
  • JavaScript side: import translation helpers from wp.i18n and use them just like in PHP.

With this setup, you can seamlessly localize strings in both PHP and JavaScript, ensuring a fully internationalized WordPress experience.