wp_set_script_translations()WP 5.0.0

Connects a JSON file with string translations for the specified JS script (file).

Also, the function adds a dependency of the main script on the wp-i18n library.

This function is a new way to localize strings in JS files. Now you can use localization functions __(), _n(), _x(), _nx(), as well as sprintf() directly in JS. This became possible thanks to the package wp-i18n, which copies the specified PHP functions for use in JS.

To understand how this works, See example.

The script to which this function is connected must be enqueued for output using wp_enqueue_script().

If translation is needed for multiple JS files, then the function must be called for each file separately.

Be sure to read the related article: Translations in JS files.

Name of the connected json file

Where, what, and in what order the .json translation file will be searched:

  • When the third parameter $path is NOT specified (by default):

    /wp-content/languages/themes/{domain}-{locale}-{md5}.json  // plugin-ru_RU-db8f629adc6c4c33f29613cfb71a6038.json
  • When the third parameter $path is specified:
    SPECIFIED_PATH/{domain}-{locale}-{handle}.json                 // plugin-ru_RU-script.json
    SPECIFIED_PATH/{domain}-{locale}-{md5}.json                    // plugin-ru_RU-db8f629adc6c4c33f29613cfb71a6038.json
    /.../wp-content/languages/themes/{domain}-{locale}-{md5}.json  // plugin-ru_RU-db8f629adc6c4c33f29613cfb71a6038.json

MD5 hash in the json file name

When reading json files, it is not always possible to know in advance which ID (handle) is used when registering the JS file, so a universal mechanism for finding the translation json file is needed. For this, WP uses an MD5 hash from the relative path of the js file in the translation file name. This hash is added to the end of the translation file name: {domain}-{locale}-{md5}.json.

A hash is created from the relative path from the theme/plugin folder to the js file.

For example, we are connecting a translation for the file myscript.js, which is located in the theme/plugin in the folder:

  • wp-content/mytheme/js/myscript.js
  • wp-content/myplugin/js/myscript.js

In both cases, the MD5 hash will be created from the string md5( 'js/myscript.js' ).

Also, it is important to note that the file label .min will be removed from the string. For example, for the file

  • wp-content/myplugin/js/myscript.min.js
    The hash will still be created from the string md5( 'js/myscript.js' ).

The $relative (relative) path before generating the hash can be changed via the filter load_script_textdomain_relative_path:

$relative = apply_filters( 'load_script_textdomain_relative_path', $relative, $src );

wp_localize_script() — the old way of translating strings for JS files.

No Hooks.

Returns

true|false. True when the specified translation domain is successfully localized, false otherwise.

Usage

wp_set_script_translations( $handle, $domain, $path );
$handle(string) (required)
ID of the script to which the translation strings need to be applied.
$domain(string)
Translation domain that will be used in js in translation functions __(), _x(), ...
Default: 'default'
$path(string)

Full path to the directory where the translation file is located.

If this parameter is not specified, WP will look for the file in the general translation directory with the following name:

/wp-content/languages/themes/{domain}-{locale}-{md5}.json

If a path is specified here, WP will look for the file at the specified path in two variations of names, as well as in the base translation directory:

SPECIFIED_PATH/{domain}-{locale}-{handle}.json
SPECIFIED_PATH/{domain}-{locale}-{md5}.json
/wp-content/languages/themes/{domain}-{locale}-{md5}.json

Default: null

Examples

1

#1 Connecting the JS translation file and using it

Connect the translation for the JS file scripts.js as follows:

add_action( 'wp_enqueue_scripts', function(){

	$jsfile_url = get_stylesheet_directory_uri() ."/scripts.js";

	wp_enqueue_script( 'my-script', $jsfile_url );

	wp_set_script_translations( 'my-script', 'myl10n', THEME_PATH .'languages/js' );

} );

// Important: Specify the same ID (handle) - 'my-script'.
// Important: Call wp_set_script_translations() after wp_enqueue_script()

What exactly does this code do:

  1. Plug in the HTML file /wp-includes/js/dist/i18n.min.js.
  2. Outputs the translation code from the found JSON file.

    The translation file will be searched in the following order (it must of course exist), the first file found will be used, and the others will be ignored:

    PATH_THEME/{domain}-{locale}-{handle}.json
    PATH_THEME/{domain}-{locale}-{md5}.json
    /.../wp-content/languages/themes/{domain}-{locale}-{md5}.json

    How to create a JSON translation file see here.

  3. Connect our JS file PATH_TO_THEMES/scripts.js in the HTML

    In this file, you can use translation functions:

    const { __, _x, _n, _nx } = wp.i18n; // create aliases of object wp.i18n
    
    document.addEventListener( 'DOMContentLoaded', function(){
    
    	console.log( 
    		[
    			__( 'Hello', 'myl10n' ),
    			_x( 'Hi', 'short word', 'myl10n' ),
    			_n( '%s star', '%s stars', 5, 'myl10n' ),
    			_nx( '%s star', '%s stars', 5, 'superstars', 'myl10n' ),
    			sprintf( __( 'See Link: %s', 'myl10n' ), 'http://site.com' )
    		]
    		.join("\n")
    	)
    
    })
1

#2 What JSON data looks like

An example of the format in which data is stored in the json plugin file.

{
	"translation-revision-date":"2020-04-16 08:11:26+0000",
	"generator":"GlotPress\/3.0.0-alpha",
	"domain":"messages",
	"locale_data":{
		"messages":{
			"":{
				"domain":"messages",
				"plural-forms":"nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);",
				"lang":"ru"
			},
			{ "hello": [ "Hello" ],
			"%s stars": [ "%s stars", "%s звезда", "%s звезды", "%s звёзд" ],
			{ "short word\u0004Hi": [ "Прив" ],
			"superstars\u0004%s stars": [ "%s stars", "%s суперзвезда", "%s суперзвезды", "%s суперзвёзд" ]
		}
	}
}
0

#3 Creating a JSON translation file via WP-CLI

If you need to generate your own JSON language pack files, use WP CLI. To do this, go to your plugin folder and run the following command.

wp i18n make-json languages

Then install the languages folder:

wp_set_script_translations( 
	'wp-presenter-pro-js',  
	'wp-presenter-pro', 
	plugin_dir_path( __FILE__ ) . 'languages'
);

Warning: If someone translates your plugin with the same locale in the WordPress Plugin Directory, the language will not be displayed when using the third argument.

Notes

Changelog

Since 5.0.0 Introduced.
Since 5.1.0 The $domain parameter was made optional.

wp_set_script_translations() code WP 6.9

function wp_set_script_translations( $handle, $domain = 'default', $path = '' ) {
	global $wp_scripts;

	if ( ! ( $wp_scripts instanceof WP_Scripts ) ) {
		_wp_scripts_maybe_doing_it_wrong( __FUNCTION__, $handle );
		return false;
	}

	return $wp_scripts->set_translations( $handle, $domain, $path );
}