load_theme_textdomain()
Load the theme's translated strings.
If the current locale exists as a .mo file in the theme's root directory, it will be included in the translated strings by the $domain.
The .mo files must be named based on the locale exactly.
No Hooks.
Return
true|false
. True when textdomain is successfully loaded, false otherwise.
Usage
load_theme_textdomain( $domain, $path );
- $domain(string) (required)
- Text domain. Unique identifier for retrieving translated strings.
- $path(string|false)
- Path to the directory containing the .mo file.
Default: false
Examples
#1 How to call a function
The function is usually called during after_setup_theme event or you can directly stick it into functions.php theme's file:
add_action( 'after_setup_theme', 'my_theme_setup' ); function my_theme_setup(){ load_theme_textdomain( 'my_theme', get_template_directory() . '/languages' ); }
First, WP will try to load the translation file from the /wp-content/language/themes
- /wp-content/language/themes/my_theme-ru_RU.mo
folder.
If there is no suitable mo file there, it will try to load it from the theme folder /wp-content/themes/my_theme/language/ru_RU.mo
.
Here my_theme
is the specified translation domain, and ru_RU
is the current locale.
#2 Switching the translation language
This example can be used when you want to switch the language. The variable passed in the URL will be used to switch the language. For example, to switch to Russian, the URL will look like this: www.example.com/?lang=ru_RU
. This will find the file ru_RU.mo, in the directory language in the theme directory:
// Changing the localization language // must be called before calling load_theme_textdomain() add_filter( 'locale', 'my_theme_localized' ); function my_theme_localized( $locale ){ if ( ! isset( $_GET['lang'] ) ) { return preg_replace( '/[^a-z_]/i', '', $_GET['lang'] ); } return $locale; } // Set the translation directory for theme // translations of the theme should be located in the `.../my_theme/languages/` directory // WordPress translations should be located in the `.../wp-content/languages` directory add_action( 'after_setup_theme', 'my_theme_setup'); function my_theme_setup(){ load_theme_textdomain( 'my_theme', get_template_directory() . '/languages' ); }
Notes
- Global. WP_Textdomain_Registry. $wp_textdomain_registry WordPress Textdomain Registry.
- Global. Array<String,. WP_Translations|NOOP_Translations> $l10n An array of all currently loaded text domains.
Changelog
Since 1.5.0 | Introduced. |
Since 4.6.0 | The function now tries to load the .mo file from the languages directory first. |
Since 6.7.0 | Translations are no longer immediately loaded, but handed off to the just-in-time loading mechanism. |