钩子文档

kses_allowed_protocols

💡 云策文档标注

概述

kses_allowed_protocols 是一个 WordPress 过滤器,用于控制 HTML 属性中允许的协议列表,如 'http'、'ftp'、'tel' 等。开发者可以通过此过滤器添加或修改允许的协议,以增强安全性或支持自定义链接类型。

关键要点

  • 过滤器名称:kses_allowed_protocols
  • 参数:$protocols(字符串数组),表示当前允许的协议列表
  • 用途:过滤 HTML 属性中的协议,防止不安全协议被使用
  • 相关函数:wp_allowed_protocols() 用于检索允许的协议列表
  • 引入版本:WordPress 3.0.0

代码示例

// 添加 Skype 协议到允许列表
add_filter( 'kses_allowed_protocols', function ( $protocols ) {
    $protocols[] = 'skype';
    return $protocols;
} );

注意事项

  • 添加协议时需谨慎,避免引入安全风险(如允许 'javascript' 协议可能导致 XSS 攻击)
  • 过滤器应在 init 之前运行,以确保在内容处理前生效
  • 示例代码要求 PHP 5.3+ 以支持匿名函数

📄 原文内容

Filters the list of protocols allowed in HTML attributes.

Parameters

$protocolsstring[]
Array of allowed protocols e.g. 'http', 'ftp', 'tel', and more.

Source

$protocols = array_unique( (array) apply_filters( 'kses_allowed_protocols', $protocols ) );

Changelog

Version Description
3.0.0 Introduced.

User Contributed Notes

  1. Skip to note 5 content

    Currently wp_kses_post will filter a URL that uses `somelink`.

    Here’s how you can allow it:

    `
    add_filter( ‘kses_allowed_protocols’, function( $protocols ) {
    $protocols[] = ‘javascript’;
    return $protocols;
    } );
    `

  2. Skip to note 6 content

    The filter should to run before init.

    Note: this example only works in PHP 5.3+

    function wpse_allow_sms_protocol( $protocols ) {
        $protocols[] = 'sms';
        return $protocols;
    }
    add_action('plugins_loaded', function(){add_filter('kses_allowed_protocols', 'wpse_allow_sms_protocol' );});
    print_r(wp_allowed_protocols());