This example demonstrates how to implement internationalization (i18n) in WordPress blocks, enabling your blocks to be translated into different languages. Learn how to properly set up translation files and functions for both PHP and JavaScript components of your blocks.
Key concepts covered:
- Translation function implementation
- Language file organization
- PHP and JavaScript i18n
- Translation loading process
- Text domain handling
| Example | Description | Tags | Download .zip | Live Demo |
|---|---|---|---|---|
| Basic Block with Translations | Shows how to implement internationalization (i18n) in a WordPress block using both PHP and JavaScript translations, demonstrating proper setup of translation files and functions. | static-rendering |
📦 |
-
JavaScript Translation
- Import translation functions
- Apply translations to strings
- Handle dynamic content
- Manage text domains
-
PHP Translation
- Register translation files
- Load language resources
- Configure text domains
- Handle script translations
-
JavaScript Side
import { __ } from '@wordpress/i18n'; // Translation in edit component function Edit() { return ( <div> <h2> { __( 'Translatable Title', 'basic-block-translations' ) } </h2> <p> { __( 'This text can be translated', 'basic-block-translations' ) } </p> </div> ); }
-
PHP Side
// Register translations for JavaScript function setup_translations() { wp_set_script_translations( 'basic-block-translations-editor-script', 'basic-block-translations', plugin_dir_path(__FILE__) . 'languages' ); } add_action('init', 'setup_translations');
-
Language Files
languages/ ├── basic-block-translations.pot # Template file ├── basic-block-translations-es_ES.po # Spanish translations ├── basic-block-translations-es_ES.mo # Compiled Spanish └── ... # Other languages -
Translation Process
- Extract translatable strings
- Create POT template
- Create language-specific PO files
- Compile to MO format
-
Use translation functions consistently
-
Provide meaningful text domains
-
Include translator comments
-
Maintain context information
-
Keep strings translatable
-
The
__function receives the text and a namespace as parameters -
At
index.phpwe tell WordPress our JavaScript contains translations, using thewp_set_script_translations()function. -
At
languages/folder there are all the translations files (the source files and the.moones actually used to apply the translations)
- WordPress i18n Documentation
- Translation Functions
- Script Translation Setup
- Language File Management
- Block Editor i18n
__()wp_set_script_translations()
Note Check the Start Guide for local development with the examples