While working on my Gutenberg Development Course I was really happy to find out that the core developers ported over much of the internationalization features we are familiar with on the PHP side into a client side library available as wp.i18n
.
Example of __() in Action
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Deconstruct just the __ function from wp.i18n global object | |
const { __ } = wp.i18n; | |
// Just pass in the text to make it available for translation | |
__( 'This text can be translated', 'textdomain' ); | |
// If used within JSX, you may need to do something like this | |
{ __( 'Translate my JSX string', 'textdomain' ) } |
Since wp.i18n is available in the global scope, you can access it directly without needing to officially “import” anything. In this example we are pulling out the __
function from the wp.i18n
library it exists within.
Notice when we call the function, we pass in a second parameter with the text domain for our plugin or theme. This is similar to how this works with PHP.
Additional Internationalization Functions
We also have access to some other helpful internationalization functions that you may recognize from the PHP side.
- wp.i18n.__()
- wp.i18n._x()
- wp.i18n._n()
- wp.i18n._nx()
- wp.i18n.sprintf()
Most of the time you only need __()
, but if you are familiar with these other functions already in PHP or just want to dig deeper, you can explore the core library readme file here.
Learn More About Gutenberg Development
If you would like to learn more about building with the new editor in WordPress, please check out my Gutenberg Development Course 🙂