WordPress 5.0: i18n support for JavaScript


For years the internationalization procedures (i18n) have been well supported by WordPress, PHP side . In this environment, WordPress provides all the tools necessary to locate its Core, plug-ins and themes. In version 5.0 of the CMS we now have the same functionality available in the Javascript environment .

When registering scripts, you can add the wp-i18n package as a dependency for allowing the addition of “translatable” strings as normally happens in a PHP environment:


wp_register_script( 'my-handle', plugins_url( '/js/my-file.js', MY_PLUGIN ), array( 'wp-i18n' ) );

While within the scripts it will be possible to use wp-18n as follows:

const { __, _x, _n, _nx } = wp.i18n;
__( '__', 'my-domain' );
_x( '_x', '_x_context', 'my-domain' );
_n( '_n_single', '_n_plural', number, 'my-domain' );
_nx( '_nx_single', '_nx_plural', number, '_nx_context', 'my-domain' );

These functions reflect their PHP counterparts and can be used in the same way. The final step will be to notify WordPress that the JavaScript scripts contain the translations, and to which type of domain they belong, to allow the same CMS to select and load only translations necessary for the current content. This with the aim of making the application as performing as possible:

wp_set_script_translations( 'my-handle', 'my-domain' );

At the moment it is possible to convey your translations using the function <code>load_textdomain</code> and passing the appropriate MO file. This is also possible using <code>wp_set_script_translations</code> a third optional parameter that represents the translation path and allows WordPress to search for the appropriate translation:

wp_set_script_translations( 'my-handle', 'my-domain', plugins_url( '/languages', MY_PLUGIN ) );

WordPress first of all checks that the file <code>${domain}-${locale}-${handle}.json</code> exists in the specified path and, if so, will use it as the source of the translations. Alternatively, it will check the path to the md5 file before turning, in the last step, to the default language directory.

It is possible to convey the files of your translations in the JED 1.x (<code>.json</code>) format. GlotPress will be able to produce this type of file in collaboration with tools such as po2json.



Please enter your comment!
Please enter your name here