函数文档

__()

💡 云策文档标注

概述

__() 是 WordPress 的核心翻译函数,用于获取指定文本的翻译字符串。它接受文本和可选的文本域参数,若未找到翻译或文本域未加载,则返回原始文本。

关键要点

  • 函数签名:__( $text, $domain = 'default' ),返回翻译后的字符串
  • 参数 $text 为必需,是要翻译的文本;$domain 可选,默认为 'default',用于标识翻译字符串的唯一文本域
  • 若无翻译或文本域未加载,函数返回原始 $text,确保代码健壮性
  • 内部调用 translate() 函数实现翻译逻辑
  • 广泛用于 WordPress 核心、主题和插件的国际化(i18n)支持

代码示例

// 基本用法:获取翻译文本
$translated_text = __( 'Hello World', 'my-text-domain' );

// 结合 echo 输出翻译(类似 _e() 函数)
echo __( 'Welcome to my site', 'my-theme' );

// 在 sprintf 中使用,避免翻译破坏链接结构
sprintf( __( 'Visit %s for more info', 'my-plugin' ), 'https://example.com' );

注意事项

  • 文本域应使用字符串字面量,而非变量,以确保翻译工具能正确解析
  • __() 返回字符串,需配合 echo 输出;若需直接输出,可使用 _e() 函数
  • 翻译字符串应避免包含动态内容(如变量),建议使用 sprintf 或类似函数处理
  • 确保文本域与 load_theme_textdomain() 或 load_plugin_textdomain() 加载的域一致

📄 原文内容

Retrieves the translation of $text.

Description

If there is no translation, or the text domain isn’t loaded, the original text is returned.

Parameters

$textstringrequired
Text to translate.
$domainstringoptional
Text domain. Unique identifier for retrieving translated strings.
Default 'default'.

Return

string Translated text.

Source

function __( $text, $domain = 'default' ) {
	return translate( $text, $domain );
}

Changelog

Version Description
2.1.0 Introduced.

User Contributed Notes

  1. Skip to note 6 content

    Make a string inside your plugin or theme translatable:

    $translated = __( 'Hello World!', 'mytextdomain' );

    ‘mytextdomain’ needs to be a unique text domain used throughout your plugin/theme. This should always be directly passed as a string literal as shown above, not a string assigned to a variable or constant. E.g., this is incorrect:

    $text_domain = 'mytextdomain';
    $string = 'Hello World!';
    $translated = __( $string, $text_domain );

    This seems to work, but it will interfere in automatic parsing of your plugin/theme’s files for translation.