函数文档

_x()

💡 云策文档标注

概述

_x() 是 WordPress 中用于获取带 gettext 上下文的翻译字符串的函数,主要用于解决相似可翻译文本在不同上下文中的冲突问题,确保翻译准确性。

关键要点

  • 函数用途:通过提供上下文信息,允许翻译者根据上下文差异翻译相同文本,避免歧义。
  • 参数说明:$text(必需,要翻译的文本)、$context(必需,上下文信息)、$domain(可选,文本域,默认为 'default')。
  • 返回值:返回翻译后的字符串(不含管道符)。
  • 内部实现:调用 translate_with_gettext_context() 函数处理翻译。
  • 相关函数:与 _ex() 等函数关联,广泛用于 WordPress 核心和插件的本地化处理。

代码示例

$translated = _x( 'Read', 'past participle: books I have read', 'textdomain' );

注意事项

  • 上下文信息应清晰描述文本使用场景,以辅助翻译者准确翻译。
  • 避免在变量上直接使用 _x(),可能导致翻译提取工具无法正确解析字符串。
  • 确保文本域正确设置,以匹配对应的翻译文件。

📄 原文内容

Retrieves translated string with gettext context.

Description

Quite a few times, there will be collisions with similar translatable text found in more than two places, but with different translated context.

By including the context in the pot file, translators can translate the two strings differently.

Parameters

$textstringrequired
Text to translate.
$contextstringrequired
Context information for the translators.
$domainstringoptional
Text domain. Unique identifier for retrieving translated strings.
Default 'default'.

Return

string Translated context string without pipe.

Source

function _x( $text, $context, $domain = 'default' ) {
	return translate_with_gettext_context( $text, $context, $domain );
}

Changelog

Version Description
2.8.0 Introduced.

User Contributed Notes

  1. Skip to note 4 content

    Example

    $translated = _x( 'Read', 'past participle: books I have read', 'textdomain' );

    Since the string ‘Read’ on its own could have one of several different meanings in English, context is given so that translators know that they should be supplying a short term that means “Books I have read.”

  2. Skip to note 5 content

    Example

    /**
     * Translates a string with context.
     *
     * @param string $text    The string to be translated.
     * @param string $context The context for the translation.
     * @param string $domain  Optional. The text domain for the translation. Default is 'default'.
     *
     * @return string The translated string.
     */
    function my_custom_translation_function( $text, $context, $domain = 'default' ) {
        // Translate the string with context
        $translated_text = _x( $text, $context, $domain );
    
        // Do some additional processing or modifications if needed
    
        return $translated_text;
    }

    Inside the function, the _x() function is called with the provided parameters to perform the translation. The resulting translated string is stored in the $translated_text variable.