函数文档

wp_kses_data()

💡 云策文档标注

概述

wp_kses_data() 是 WordPress 中用于内容过滤的函数,基于 KSES 规则移除不允许的 HTML 标签,确保数据安全。它期望输入未转义的数据,并返回过滤后的字符串。

关键要点

  • 函数用途:使用允许的 HTML KSES 规则过滤内容,防止不安全代码注入。
  • 参数要求:$data 参数为字符串类型,必须是未转义的内容。
  • 返回值:返回过滤后的字符串,仅保留允许的 HTML 标签和属性。
  • 内部实现:调用 wp_kses() 函数,并使用 current_filter() 作为第二个参数来确定允许的 HTML 规则。
  • 相关函数:与 wp_kses() 和 current_filter() 紧密相关,常用于 sanitize_option() 等场景。
  • 版本历史:自 WordPress 2.9.0 版本引入。

代码示例

$s = 'Foo<script>alert("Bar");</script>';
$x = wp_kses_data($s);
// 现在,$x 是 Fooalert("Bar");

注意事项

  • 输入数据必须未转义,否则可能导致过滤不准确或错误。
  • 允许的 HTML 标签由全局变量 $allowedtags 定义,可通过 wp_kses_allowed_html 过滤器自定义,需检查第二个参数是否为 'data'。
  • 示例中展示了如何查看 $allowedtags 内容,以了解默认允许的标签和属性。

📄 原文内容

Sanitize content with allowed HTML KSES rules.

Description

This function expects unslashed data.

Parameters

$datastringrequired
Content to filter, expected to not be escaped.

Return

string Filtered content.

Source

function wp_kses_data( $data ) {
	return wp_kses( $data, current_filter() );
}

Changelog

Version Description
2.9.0 Introduced.

User Contributed Notes

  1. Skip to note 4 content

    To find out what tags are allowed in this function, just access global $allowedtags;. The code here…

    global $allowedtags;
    var_dump($allowedtags);

    …outputs the following:

    array (size=14)
        'a' => array (size=2)
            'href' => boolean true
            'title' => boolean true
    
        'abbr' => array (size=1)
            'title' => boolean true
    
        'acronym' => array (size=1)
            'title' => boolean true
    
        'b' => array (size=0)
    
        'blockquote' => array (size=1)
            'cite' => boolean true
    
        'cite' => array (size=0)
    
        'code' => array (size=0)
    
        'del' => array (size=1)
            'datetime' => boolean true
    
        'em' => array (size=0)
    
        'i' => array (size=0)
    
        'q' => array (size=1)
            'cite' => boolean true
    
        's' => array (size=0)
    
        'strike' => array (size=0)
    
        'strong' => array (size=0)

    And if you wish to modify it to customize the allowed/disallowed tags for everything that uses this function, you can do so using the wp_kses_allowed_html filter and check that the second parameter is equal to 'data'.