函数文档

wp_kses_post()

💡 云策文档标注

概述

wp_kses_post() 函数用于对文章内容进行 HTML 标签过滤,确保只保留允许的标签和属性,常用于安全地输出用户生成的内容。

关键要点

  • 函数基于 wp_kses() 实现,使用 'post' 上下文来定义允许的 HTML 标签和属性。
  • 参数 $data 为必需,接受未转义的数据字符串,返回过滤后的安全内容。
  • 主要用于文章类型的内容,而非表单 $_POST 数据,确保输出安全。

代码示例

if ( ! version_compare( PHP_VERSION, '5.6', '>=' ) ) {
    add_action( 'admin_notices', 'wpdocs_fail_php_version' );
}

function wpdocs_fail_php_version() {
    if ( isset( $_GET['activate'] ) ) {
        unset( $_GET['activate'] );
    }
    $message = sprintf( __( 'My Custom Plugin requires PHP version %s+, plugin is currently NOT RUNNING.', 'wpdocs-text-domain' ), '5.6' );
    $html_message = sprintf( '%s', wpautop( $message ) );
    echo wp_kses_post( $html_message );
}

📄 原文内容

Sanitizes content for allowed HTML tags for post content.

Description

Post content refers to the page contents of the ‘post’ type and not $_POST data from forms.

This function expects unslashed data.

Parameters

$datastringrequired
Post content to filter.

Return

string Filtered post content with allowed HTML tags and attributes intact.

Source

function wp_kses_post( $data ) {
	return wp_kses( $data, 'post' );
}

Changelog

Version Description
2.9.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Display Admin notice

    The following example of basic usage of the wp_kses_post() function. We can use it to print the message in the admin screen.

    if ( ! version_compare( PHP_VERSION, '5.6', '>=' ) ) {
    	add_action( 'admin_notices', 'wpdocs_fail_php_version' );
    } 
    
    /**
     * Admin notice for minimum PHP version.
     *
     * Warning when the site doesn't have the minimum required PHP version.
     *
     * @since 1.0.0
     *
     * @return void
     */
    function wpdocs_fail_php_version() {
    
    	if ( isset( $_GET['activate'] ) ) {
    		unset( $_GET['activate'] );
    	}
    
    	/* translators: %s: PHP version */
    	$message      = sprintf( __( '<strong>My Custom Plugin</strong> requires PHP version %s+, plugin is currently NOT RUNNING.', 'wpdocs-text-domain' ), '5.6' );
    	$html_message = sprintf( '<div class="error">%s</div>', wpautop( $message ) );
    	echo wp_kses_post( $html_message );
    }