esc_html__()
云策文档标注
概述
esc_html__() 是一个 WordPress 函数,用于获取文本的翻译并对其进行 HTML 转义,确保在 HTML 输出中安全使用。如果翻译不存在或文本域未加载,则返回转义后的原始文本。
关键要点
- 函数作用:结合翻译和 HTML 转义,防止 XSS 攻击,提升安全性。
- 参数说明:$text(必需,要翻译的文本)和 $domain(可选,文本域,默认为 'default')。
- 返回值:返回转义后的翻译字符串。
- 相关函数:与 translate() 和 esc_html() 关联,用于内部处理。
- 使用场景:常用于插件或主题开发中,在 HTML 内嵌入翻译文本,确保第三方翻译内容的安全性。
代码示例
function esc_html__( $text, $domain = 'default' ) {
return esc_html( translate( $text, $domain ) );
}注意事项
- 与 esc_html_e() 区别:esc_html__() 返回字符串,而 esc_html_e() 直接输出字符串。
- 安全重要性:必须使用此函数处理用户生成或翻译的 HTML 内容,以避免代码注入风险。
原文内容
Retrieves the translation of $text and escapes it for safe use in HTML output.
Description
If there is no translation, or the text domain isn’t loaded, the original text is escaped and returned.
Parameters
$textstringrequired-
Text to translate.
$domainstringoptional-
Text domain. Unique identifier for retrieving translated strings.
Default'default'.
Source
function esc_html__( $text, $domain = 'default' ) {
return esc_html( translate( $text, $domain ) );
}
Changelog
| Version | Description |
|---|---|
| 2.8.0 | Introduced. |
Skip to note 4 content
izem
Use to embed translations inside HTML. This way you ensure that third party translation are sanitized and will not break the code (proper security to keep the users safe).
<h1></h3>Skip to note 5 content
danieltj
When using
esc_html__, remember that it’s also possible to echo the string value out by using the relatedesc_html_ewhich does the same thing but echoes the string too.An example:
<p></p>You can also read more about
esc_html_etoo.Skip to note 6 content
Mehraz Morshed
esc_html() is for escaping.
esc_html__() is for translating and escaping.
esc_html_e() is for translating, escaping and directly echoing.