load_textdomain() │ WP 1.5.0
Подключает указанный файл перевода.
Функция парсит указанный в параметрах .mo файл и добавляет данные из него в данные переводов WordPress - в глобальную переменную $l10n :
$l10n[ $domain ] = & $mo;
Если указанный домен уже существует в данных, то подключаемые строки локализации объединяться с имеющимися (сливаются в единый массив).
Файл перевода должен быть подключен до того, как он будет использован. Поэтому load_textdomain() принято вызывать во время события plugins_loaded .
Для перевода любой строки в WordPress, у строки должен быть перевод, а чтобы он был нужно подключить данные перевода, среди которых будет перевод нужной строки. Подключить данные перевода, а именно загрузить .mo файл перевода в глобальные данные локализации можно с помощью:
Возвращает
true|false
. Вернет false, если .mo файл не существует по указанному пути. В остальных случаях функция вернет true.
Использование
load_textdomain( $domain, $mofile )
$domain(строка) (обязательный)
Уникальный идентификатор, по которому, для перевода строки, в дальнейшем можно будет обращаться.
$mofile(строка) (обязательный)
Абсолютный путь до .mo файла (home/example.com/wp-content/plugins/my-plugin.mo ).
$locale(строка) (WP 6.1)
Локаль.
По умолчанию: null (текущая локаль)
Примеры
#1 Перевод строки в WordPress
В этом примере переведем строку __('book', 'mydomain')
. Подразумевается, что .mo файл для перевода уже создан и в нем есть данные для перевода этой строки:
// здесь .mo файл должен лежать в папке lang, которая находится в папке где находится сам файл в котором вызывается эта строка
// Подключаем имеющийся файл .mo (название файла: ru_RU.mo или другое, зависит от локали)
add_action( 'plugins_loaded', 'load_my_textdomain' );
function load_my_textdomain(){
$mo_file_path = __DIR__ . '/lang/'. determine_locale() . '.mo';
load_textdomain( 'mydomain', $mo_file_path );
}
Для версий WP меньше 5.0 используйте get_locale() вместо determine_locale() .
Теперь в теме используем:
<?php _e( 'book', 'mydomain' ); ?>
Выведет "книга".
Добавить свой пример
Заметки
Global. MO[]. $l10n An array of all currently loaded text domains.
Global. MO[]. $l10n_unloaded An array of all text domains that have been unloaded again.
Global. WP_Textdomain_Registry. $wp_textdomain_registry WordPress Textdomain Registry.
Список изменений
С версии 1.5.0
Введена.
С версии 6.1.0
Added the $locale parameter.
Код load_textdomain() load textdomain
WP 6.7.1
function load_textdomain( $domain, $mofile, $locale = null ) {
/** @var WP_Textdomain_Registry $wp_textdomain_registry */
global $l10n, $l10n_unloaded, $wp_textdomain_registry;
$l10n_unloaded = (array) $l10n_unloaded;
if ( ! is_string( $domain ) ) {
return false;
}
/**
* Filters whether to short-circuit loading .mo file.
*
* Returning a non-null value from the filter will effectively short-circuit
* the loading, returning the passed value instead.
*
* @since 6.3.0
*
* @param bool|null $loaded The result of loading a .mo file. Default null.
* @param string $domain Text domain. Unique identifier for retrieving translated strings.
* @param string $mofile Path to the MO file.
* @param string|null $locale Locale.
*/
$loaded = apply_filters( 'pre_load_textdomain', null, $domain, $mofile, $locale );
if ( null !== $loaded ) {
if ( true === $loaded ) {
unset( $l10n_unloaded[ $domain ] );
}
return $loaded;
}
/**
* Filters whether to override the .mo file loading.
*
* @since 2.9.0
* @since 6.2.0 Added the `$locale` parameter.
*
* @param bool $override Whether to override the .mo file loading. Default false.
* @param string $domain Text domain. Unique identifier for retrieving translated strings.
* @param string $mofile Path to the MO file.
* @param string|null $locale Locale.
*/
$plugin_override = apply_filters( 'override_load_textdomain', false, $domain, $mofile, $locale );
if ( true === (bool) $plugin_override ) {
unset( $l10n_unloaded[ $domain ] );
return true;
}
/**
* Fires before the MO translation file is loaded.
*
* @since 2.9.0
*
* @param string $domain Text domain. Unique identifier for retrieving translated strings.
* @param string $mofile Path to the .mo file.
*/
do_action( 'load_textdomain', $domain, $mofile );
/**
* Filters MO file path for loading translations for a specific text domain.
*
* @since 2.9.0
*
* @param string $mofile Path to the MO file.
* @param string $domain Text domain. Unique identifier for retrieving translated strings.
*/
$mofile = apply_filters( 'load_textdomain_mofile', $mofile, $domain );
if ( ! $locale ) {
$locale = determine_locale();
}
$i18n_controller = WP_Translation_Controller::get_instance();
// Ensures the correct locale is set as the current one, in case it was filtered.
$i18n_controller->set_locale( $locale );
/**
* Filters the preferred file format for translation files.
*
* Can be used to disable the use of PHP files for translations.
*
* @since 6.5.0
*
* @param string $preferred_format Preferred file format. Possible values: 'php', 'mo'. Default: 'php'.
* @param string $domain The text domain.
*/
$preferred_format = apply_filters( 'translation_file_format', 'php', $domain );
if ( ! in_array( $preferred_format, array( 'php', 'mo' ), true ) ) {
$preferred_format = 'php';
}
$translation_files = array();
if ( 'mo' !== $preferred_format ) {
$translation_files[] = substr_replace( $mofile, ".l10n.$preferred_format", - strlen( '.mo' ) );
}
$translation_files[] = $mofile;
foreach ( $translation_files as $file ) {
/**
* Filters the file path for loading translations for the given text domain.
*
* Similar to the {@see 'load_textdomain_mofile'} filter with the difference that
* the file path could be for an MO or PHP file.
*
* @since 6.5.0
* @since 6.6.0 Added the `$locale` parameter.
*
* @param string $file Path to the translation file to load.
* @param string $domain The text domain.
* @param string $locale The locale.
*/
$file = (string) apply_filters( 'load_translation_file', $file, $domain, $locale );
$success = $i18n_controller->load_file( $file, $domain, $locale );
if ( $success ) {
if ( isset( $l10n[ $domain ] ) && $l10n[ $domain ] instanceof MO ) {
$i18n_controller->load_file( $l10n[ $domain ]->get_filename(), $domain, $locale );
}
// Unset NOOP_Translations reference in get_translations_for_domain().
unset( $l10n[ $domain ] );
$l10n[ $domain ] = new WP_Translations( $i18n_controller, $domain );
$wp_textdomain_registry->set( $domain, $locale, dirname( $file ) );
return true;
}
}
return false;
}
Cвязанные функции