translate()
云策文档标注
概述
translate() 函数用于检索指定文本的翻译,是 WordPress 国际化(i18n)的核心函数之一。它通过文本域(domain)获取翻译,并支持过滤器钩子进行自定义处理。
关键要点
- 函数返回 $text 的翻译字符串,若无翻译或文本域未加载,则返回原始文本。
- 参数 $text 为必需,表示要翻译的文本;$domain 为可选,指定文本域,默认为 'default'。
- 不建议直接使用 translate(),应优先使用 __() 或相关包装函数(如 esc_attr__()、_e() 等)。
- 函数内部调用 get_translations_for_domain() 获取翻译实例,并应用 gettext 和 gettext_{$domain} 过滤器。
- 自 WordPress 5.5.0 起,新增了动态钩子 gettext_{$domain},允许按文本域过滤翻译。
代码示例
function translate( $text, $domain = 'default' ) {
$translations = get_translations_for_domain( $domain );
$translation = $translations->translate( $text );
$translation = apply_filters( 'gettext', $translation, $text, $domain );
$translation = apply_filters( "gettext_{$domain}", $translation, $text, $domain );
return $translation;
}注意事项
- 直接调用 translate() 可能导致翻译上下文丢失或安全问题,建议使用更高级的包装函数。
- 确保文本域正确加载,否则翻译可能无法生效。
- 利用 gettext 和 gettext_{$domain} 钩子可以自定义翻译逻辑或添加额外处理。
原文内容
Retrieves the translation of $text.
Description
If there is no translation, or the text domain isn’t loaded, the original text is returned.
_Note:_ Don’t use translate() directly, use __() or related functions.
Parameters
$textstringrequired-
Text to translate.
$domainstringoptional-
Text domain. Unique identifier for retrieving translated strings.
Default'default'.
Source
function translate( $text, $domain = 'default' ) {
$translations = get_translations_for_domain( $domain );
$translation = $translations->translate( $text );
/**
* Filters text with its translation.
*
* @since 2.0.11
*
* @param string $translation Translated text.
* @param string $text Text to translate.
* @param string $domain Text domain. Unique identifier for retrieving translated strings.
*/
$translation = apply_filters( 'gettext', $translation, $text, $domain );
/**
* Filters text with its translation for a domain.
*
* The dynamic portion of the hook name, `$domain`, refers to the text domain.
*
* @since 5.5.0
*
* @param string $translation Translated text.
* @param string $text Text to translate.
* @param string $domain Text domain. Unique identifier for retrieving translated strings.
*/
$translation = apply_filters( "gettext_{$domain}", $translation, $text, $domain );
return $translation;
}
Hooks
- apply_filters( ‘gettext’, string $translation, string $text, string $domain )
-
Filters text with its translation.
- apply_filters( “gettext_{$domain}”, string $translation, string $text, string $domain )
-
Filters text with its translation for a domain.