函数文档

is_textdomain_loaded()

💡 云策文档标注

概述

is_textdomain_loaded() 函数用于检查指定文本域的翻译是否已加载。它通过全局变量 $l10n 判断翻译是否存在且非 NOOP_Translations 实例。

关键要点

  • 参数 $domain 为必需,是文本域的唯一标识符,用于检索翻译字符串。
  • 返回布尔值,表示翻译是否已加载。
  • 函数内部检查 $l10n[$domain] 是否设置且不是 NOOP_Translations 类型。
  • 在 WordPress 3.0.0 版本中引入。

代码示例

if ( is_textdomain_loaded( $plugin ) ) {
    unload_textdomain( $plugin );
}
$mofile = sprintf( '%s-%s.mo', $plugin, $locale );
$domain_path = path_join( WP_LANG_DIR, 'plugins' );
load_textdomain( $plugin, path_join( $domain_path, $mofile ) );

if ( ! $loaded ) {
    $domain_path = path_join( WP_PLUGIN_DIR, "{$plugin}/languages" );
    $loaded = load_textdomain( $plugin, path_join( $domain_path, $mofile ) );
}

注意事项

在多语言网站中,可能需要加载与当前用户区域不同的插件翻译区域。使用此函数可检查并卸载已加载的翻译,然后加载指定区域的翻译文件。


📄 原文内容

Determines whether there are translations for the text domain.

Parameters

$domainstringrequired
Text domain. Unique identifier for retrieving translated strings.

Return

bool Whether there are translations.

Source

function is_textdomain_loaded( $domain ) {
	global $l10n;
	return isset( $l10n[ $domain ] ) && ! $l10n[ $domain ] instanceof NOOP_Translations;
}

Changelog

Version Description
3.0.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    There are situations where one requires a plugin translation locale to be loaded which is different from the current user locale.

    For example, in multilingual websites, creating a translation of a post/widget requires some translations to be loaded for a given plugin text domain. The user locale (dashboard locale) is loaded by default, so it is important to unload that if it has been loaded already and seek the translation file to load for the text domain for the requested locale,

    if ( is_textdomain_loaded( $plugin ) ) {
    	unload_textdomain( $plugin );
    }
    $mofile = sprintf( '%s-%s.mo', $plugin, $locale );
    //check the installation language path first.
    $domain_path = path_join( WP_LANG_DIR, 'plugins' );
    load_textdomain( $plugin, path_join( $domain_path, $mofile ) );
    
    if ( ! $loaded ) { //else, check the plugin language folder.
    	$domain_path = path_join( WP_PLUGIN_DIR, "{$plugin}/languages" );
    	$loaded = load_textdomain( $plugin, path_join( $domain_path, $mofile ) );
    }