gettext_with_context
云策文档标注
概述
gettext_with_context 是一个 WordPress 过滤器钩子,用于基于上下文信息过滤翻译文本。它主要应用于处理上下文的国际化函数,如 _x()、_ex()、esc_attr_x() 和 esc_html_x()。
关键要点
- 过滤器钩子名称为 gettext_with_context,参数包括 $translation(翻译后的文本)、$text(待翻译文本)、$context(上下文信息)和 $domain(文本域)。
- 此钩子始终应用,即使国际化未启用或文本域未加载,可能导致性能问题,需谨慎使用。
- 与常规翻译函数(如 _e())和复数处理函数(如 _n())相关,具体用法可参考 gettext() 和 ngettext() 文档。
代码示例
/**
* @param string $translated
* @param string $text
* @param string $context
* @param string $domain
* @return string
*/
function example_gettext_with_context( $translated, $text, $context, $domain ) {
if ( 'example-plugin' == $domain ) {
if ( 'directions' == $text && 'directions on map' == $context ) {
$translated = 'map directions'; // not recipe instructions!
}
}
return $translated;
}
add_filter( 'gettext_with_context', 'example_gettext_with_context', 10, 4 );注意事项
此过滤器在任何情况下都会运行,包括国际化未生效或文本域未加载时,因此如果添加了钩子函数,它们将始终执行,可能影响性能,开发者需注意优化。
原文内容
Filters text with its translation based on context information.
Parameters
$translationstring-
Translated text.
$textstring-
Text to translate.
$contextstring-
Context information for the translators.
$domainstring-
Text domain. Unique identifier for retrieving translated strings.
Source
$translation = apply_filters( 'gettext_with_context', $translation, $text, $context, $domain );
Changelog
| Version | Description |
|---|---|
| 2.8.0 | Introduced. |
Skip to note 2 content
leogermani
/** * @param string $translated * @param string $text * @param string $context * @param string $domain * @return string */ function example_gettext_with_context( $translated, $text, $context, $domain ) { if ( 'example-plugin' == $domain ) { if ( 'directions' == $text && 'directions on map' == $context ) { $translated = 'map directions'; // not recipe instructions! } } return $translated; } add_filter( 'gettext_with_context', 'example_gettext_with_context', 10, 4 );