esc_attr__()
云策文档标注
概述
esc_attr__() 是一个 WordPress 函数,用于获取文本的翻译并转义,以便安全地用于 HTML 属性中。它结合了翻译和转义功能,确保输出在属性上下文中是安全的。
关键要点
- 函数 esc_attr__($text, $domain = 'default') 接受两个参数:$text(必需,要翻译的文本)和 $domain(可选,文本域,默认为 'default')。
- 返回值为字符串:成功时返回翻译后的文本,失败时返回原始文本。
- 内部实现基于 translate() 和 esc_attr() 函数,先翻译再转义。
- 常用于 WordPress 核心和管理界面中,如菜单、小部件、媒体处理等场景,以确保国际化文本在属性中的安全性。
代码示例
function esc_attr__( $text, $domain = 'default' ) {
return esc_attr( translate( $text, $domain ) );
}注意事项
- 如果翻译不存在或文本域未加载,函数会返回原始文本,避免中断输出。
- 自 WordPress 2.8.0 版本引入,是处理属性中翻译文本的标准方法。
原文内容
Retrieves the translation of $text and escapes it for safe use in an attribute.
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'.
Source
function esc_attr__( $text, $domain = 'default' ) {
return esc_attr( translate( $text, $domain ) );
}
Changelog
| Version | Description |
|---|---|
| 2.8.0 | Introduced. |