New! JavaScript i18n support in WordPress 5.0

For years, internationalization (i18ni18n Internationalization, or the act of writing and preparing code to be fully translatable into other languages. Also see localization. Often written with a lowercase i so it is not confused with a lowercase L or the numeral 1. Often an acquired skill.) has been a thing that has been pretty well supported in WordPress when it comes to PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher development. For PHP, WordPress already provides all the tools necessary to make it as easy as possible to localize WordPress coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress., themes and plugins to any language. Today we are bringing the same capabilities to JavaScriptJavaScript JavaScript or JS is an object-oriented computer programming language commonly used to create interactive effects within web browsers. WordPress makes extensive use of JS for a better user experience. While PHP is executed on the server, JS executes within a user’s browser. https://www.javascript.com/. development for WordPress.

How does it work?

When registering your scripts you can add wp-i18n as a dependency to allow you to add translatable strings as you would in PHP:

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

Inside your scripts you will then be able 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 mirror their PHP counterparts and can be used in exactly the same manner. 

The final step is to tell WordPress your script contains translations and of which domain, this is to allow WordPress to selectively load only the necessary translations to ensure everything is as fast as can be:

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

Make sure to also specify the Text Domain for your translations in the headerHeader The header of your site is typically the first thing people will experience. The masthead or header art located across the top of your page is part of the look and feel of your website. It can influence a visitor’s opinion about your content and you/ your organization’s brand. It may also look different on different screen sizes. of your pluginPlugin A plugin is a piece of software containing a group of functions that can be added to a WordPress website. They can extend functionality or add new features to your WordPress websites. WordPress plugins are written in the PHP programming language and integrate seamlessly with WordPress. These can be free in the WordPress.org Plugin Directory https://wordpress.org/plugins/ or can be cost-based plugin from a third-party file. Otherwise the translations will not be picked up by translate.wordpress.org

Advanced usage

Right now it’s already possible to ship your own translations using the load_textdomain function and passing your own MO file. This is also possible using wp_set_script_translations which accepts an optional third path argument that allows you to tell WordPress to first look elsewhere for translations:

wp_set_script_translations( 'my-handle', 'my-domain', plugin_dir_path( MY_PLUGIN ) . 'languages' );

If passed WordPress will first check if a file in the format of ${domain}-${localeLocale A locale is a combination of language and regional dialect. Usually locales correspond to countries, as is the case with Portuguese (Portugal) and Portuguese (Brazil). Other examples of locales include Canadian English and U.S. English.}-${handle}.jsonJSON JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML. exists in the given path and use it as the source of translations if so. Alternatively it will also first check the given path for the md5 filename before defaulting to the WordPress languages directory.

If you want to ship your own translationtranslation The process (or result) of changing text, words, and display formatting to support another language. Also see localization, internationalization. files these should be in the JED 1.x ( .json ) format. GlotPress is able to create these along with other tools such as po2json. Ideally these files should only contain translations that occur within their respective JSJS JavaScript, a web scripting language typically executed in the browser. Often used for advanced user interfaces and behaviors. files. With po2json you can generate these files as follows:

po2json translation.po translation.json -f jed

This will generate a JSON in the following format:

{
  "translation-revision-date": "+0000",
  "generator":                 "GlotPress/2.3.0-alpha",
  "domain":                    "messages",
  "locale_data":               {
    "messages": {
      "":                                                             {
        "domain":       "messages",
        "plural-forms": "nplurals=2; plural=n != 1",
        "lang":         "en-gb"
      },
      "This file is too big. Files must be less than %d KB in size.": [
        "This file is too big. Files must be less than %d KB in size."
      ],
      "%d Theme Update":                                              [
        "%d Theme Update",
        "%d Theme Updates"
      ],
      "password strength\u0004Medium":                                [
        "Medium"
      ],
      "taxonomy singular name\u0004Category":                         [
        "Category"
      ],
      "post type general name\u0004Pages":                            [
        "Pages"
      ]
    }
  }
}

Behind the screens

When you upload your plugin or theme to wordpress.org all JS files will automatically be parsed the same as is already being done for PHP files. Any detected translations will be added to translate.wordpress.org to allow the community to cooperate to ensure WordPress, plugins and themes are available in as many languages as possible.

In order to parse all JS files the i18n-command for wp-cli is used. This replaces makepot.php to not only allow picking up translations in JS files but also to audit strings, parse strings only of a specific text domain and even pick up a few strings that weren’t detected by makepot.php. This command is freely available and open-source as makepot.php was and it’s recommended that anyone using makepot.php transition over to this much improved replacement.

Based on these parsed translations Language Packs are generated. Traditionally these used to only contain PO and MO files, one pair for each locale. In order to selectively load only the necessary translations regardless of whether it’s used or not a few more files are being added, one JSON file for every JS file that contains translations per locale.

When parsing JS files for translations we don’t know which handle is used to register that file so we’ve had to use an alternate mechanism to find the translations belonging to each file. To do this we’re using the md5 of the relative path of each file. This is appended to the usual name of ${domain}-${locale} in the form of ${domain}-${locale}-${md5}.json.

When you set script translations for a handle WordPress will automatically figure out the relative md5 hash of your source file, check to see if a translations file exists and if so ensure that it’s loaded into wp.i18n before your script runs.

Plugin and theme support

Translation and Language packs support for plugins and themes that are hosted on the repo is expected in the upcoming weeks. The patches are ready and waiting for commit. Plugin and theme authors are encouraged to start using wp-i18n in their JavaScript projects.

Credits

This APIAPI An API or Application Programming Interface is a software intermediary that allows programs to interact with each other and share data in limited, clearly defined ways. wouldn’t have been possible without the long standing efforts of @ocean90, @swissspidy, @nerrad, @atimmer, @schlessera and more recently @herregroen. Thanks a ton for the incredible work you’ve all put into making this a reality! Another thanks to @herregroen for providing the necessary input for this devnotedev note Each important change in WordPress Core is documented in a developers note, (usually called dev note). Good dev notes generally include a description of the change, the decision that led to this change, and a description of how developers are supposed to work with that change. Dev notes are published on Make/Core blog during the beta phase of WordPress release cycle. Publishing dev notes is particularly important when plugin/theme authors and WordPress developers need to be aware of those changes.In general, all dev notes are compiled into a Field Guide at the beginning of the release candidate phase..

#5-0, #dev-notes, #i18n