函数文档

esc_html()

💡 云策文档标注

概述

esc_html() 是 WordPress 核心函数,用于对 HTML 块内容进行转义,防止跨站脚本攻击(XSS)。它通过清理无效 UTF-8 字符并转换特殊字符为 HTML 实体,确保输出内容在 HTML 中安全显示。

关键要点

  • 函数接受一个字符串参数 $text,返回转义后的安全字符串。
  • 内部调用 wp_check_invalid_utf8() 和 _wp_specialchars() 进行字符处理。
  • 通过 apply_filters('esc_html', $safe_text, $text) 钩子允许过滤转义后的字符串。
  • 避免对已包含 HTML 链接的内容使用,否则可能导致链接失效。
  • 与翻译函数结合使用时有 esc_html__()、esc_html_e() 和 esc_html_x() 等变体。

代码示例

$html = esc_html( '<a href="http://www.example.com/">A link</a>' );
// 输出:&lt;a href=&quot;http://www.example.com/&quot;&gt;A link&lt;/a&gt;

注意事项

  • esc_html() 会避免双重编码,例如输入 'A & B' 输出 'A & B' 而非 'A &amp; B'。
  • 不应用于需要保留 HTML 功能的内容(如链接),否则会破坏其结构。
  • 自 WordPress 2.8.0 版本引入,是输出安全的重要工具。

📄 原文内容

Escaping for HTML blocks.

Parameters

$textstringrequired

Return

string

Source

function esc_html( $text ) {
	$safe_text = wp_check_invalid_utf8( $text );
	$safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
	/**
	 * Filters a string cleaned and escaped for output in HTML.
	 *
	 * Text passed to esc_html() is stripped of invalid or special characters
	 * before output.
	 *
	 * @since 2.8.0
	 *
	 * @param string $safe_text The text after it has been escaped.
	 * @param string $text      The text prior to being escaped.
	 */
	return apply_filters( 'esc_html', $safe_text, $text );
}

Hooks

apply_filters( ‘esc_html’, string $safe_text, string $text )

Filters a string cleaned and escaped for output in HTML.

Changelog

Version Description
2.8.0 Introduced.

User Contributed Notes

  1. Skip to note 6 content

    Examples

    $html = esc_html( '<a href="<a href="http://www.example.com/">A" rel="nofollow ugc">http://www.example.com/">A</a> link</a>' );

    $html now contains this:

    <a href="<a href="http://www.example.com/">A" rel="nofollow ugc">http://www.example.com/">A</a> link</a>

    which would be displayed in an HTML document as:

    <a href="A” rel=”nofollow ugc”>http://www.example.com/”>A link

    Instead of like this:

    A link