函数文档

esc_attr_x()

💡 云策文档标注

概述

esc_attr_x() 是一个 WordPress 函数,用于在翻译字符串时提供上下文信息,并转义输出以确保在 HTML 属性中安全使用。

关键要点

  • 函数 esc_attr_x( $text, $context, $domain = 'default' ) 接受三个参数:$text(必需,要翻译的文本)、$context(必需,翻译上下文)、$domain(可选,文本域,默认为 'default')。
  • 返回转义后的翻译字符串,若无翻译或文本域未加载,则返回转义后的原始文本。
  • 内部调用 translate_with_gettext_context() 进行翻译,然后使用 esc_attr() 进行转义。
  • 自 WordPress 2.8.0 版本引入,常用于需要本地化且安全输出的场景,如搜索表单、密码表单等。

代码示例

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

📄 原文内容

Translates string with gettext context, 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 escaped and returned.

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 text.

Source

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

Changelog

Version Description
2.8.0 Introduced.