@wordpress/i18n package provides JavaScript utilities that mirror WordPress’s PHP internationalization functions.
Installation
Install the i18n package:Core Translation Functions
Basic Translation: __()
The__() function retrieves translated text:
Contextual Translation: _x()
Use_x() when the same string needs different translations based on context:
- UI Context
- Content Context
Plural Forms: _n()
Handle singular and plural forms correctly:Plural Forms with Context: _nx()
Combine pluralization with context:String Formatting with sprintf()
Thesprintf() function formats strings with placeholders:
Format Specifiers:
%s- String%d- Integer%f- Float%1$s,%2$d- Positional arguments (recommended for translations)
Block Registration Example
Translate block metadata and content:Inspector Controls Example
Translate panel labels and help text:Dynamic Content Example
Combine translations with dynamic values:RTL (Right-to-Left) Support
Check if the current locale uses RTL:Managing Locale Data
Setting Locale Data
Load translation data programmatically:Checking Translations
Best Practices
Use Consistent Text Domains
Avoid String Concatenation
Provide Context for Translators
Use Positional Arguments
Extract Full Sentences
Common Patterns
Loading States
Error Messages
Conditional Messages
WordPress Script Translations
When enqueueing JavaScript files, set the text domain for automatic translation loading:Translation File Generation
Use WP-CLI to extract translatable strings:Testing Translations
Test your translations with different locales:Common Mistakes to Avoid
-
Don’t use variables as translatable strings:
-
Don’t concatenate translations:
-
Don’t split sentences:
Next Steps
- Learn about Data Management for dynamic content
- Explore Filters and Hooks for extending functionality
- Read the WordPress i18n documentation
- Check the @wordpress/i18n package reference