函数文档

wp_allowed_protocols()

💡 云策文档标注

概述

wp_allowed_protocols() 函数用于获取在 HTML 属性中允许的协议列表,常用于 URL 过滤和安全处理。默认返回包含常见协议(如 http、https、mailto 等)的数组,但排除了 'javascript' 协议以增强安全性。

关键要点

  • 函数返回一个字符串数组,表示允许的协议列表,默认包括 http、https、ftp、ftps、mailto、news、irc、irc6、ircs、gopher、nntp、feed、telnet、mms、rtsp、sms、svn、tel、fax、xmpp、webcal 和 urn。
  • 通过 apply_filters('kses_allowed_protocols', $protocols) 钩子可以过滤和修改允许的协议列表,但仅在 wp_loaded 动作未触发时应用。
  • 此函数与 wp_kses() 和 esc_url() 相关,常用于确保 URL 安全,防止恶意代码注入。

代码示例

function wp_allowed_protocols() {
	static $protocols = array();

	if ( empty( $protocols ) ) {
		$protocols = array( 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'irc6', 'ircs', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'sms', 'svn', 'tel', 'fax', 'xmpp', 'webcal', 'urn' );
	}

	if ( ! did_action( 'wp_loaded' ) ) {
		/**
		 * Filters the list of protocols allowed in HTML attributes.
		 *
		 * @since 3.0.0
		 *
		 * @param string[] $protocols Array of allowed protocols e.g. 'http', 'ftp', 'tel', and more.
		 */
		$protocols = array_unique( (array) apply_filters( 'kses_allowed_protocols', $protocols ) );
	}

	return $protocols;
}

注意事项

  • 默认协议列表覆盖了常见链接协议,但排除了 'javascript',以防止不受信任用户执行脚本,开发者应避免添加此协议。
  • 过滤钩子 kses_allowed_protocols 仅在 wp_loaded 动作之前生效,确保在适当时机修改协议列表。
  • 函数是静态缓存实现,首次调用后结果会被缓存,提高性能。

📄 原文内容

Retrieves a list of protocols to allow in HTML attributes.

Description

See also

Return

string[] Array of allowed protocols. Defaults to an array containing 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'irc6', 'ircs', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'sms', 'svn', 'tel', 'fax', 'xmpp', 'webcal', and 'urn'.
This covers all common link protocols, except for 'javascript' which should not be allowed for untrusted users.

Source

function wp_allowed_protocols() {
	static $protocols = array();

	if ( empty( $protocols ) ) {
		$protocols = array( 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'irc6', 'ircs', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'sms', 'svn', 'tel', 'fax', 'xmpp', 'webcal', 'urn' );
	}

	if ( ! did_action( 'wp_loaded' ) ) {
		/**
		 * Filters the list of protocols allowed in HTML attributes.
		 *
		 * @since 3.0.0
		 *
		 * @param string[] $protocols Array of allowed protocols e.g. 'http', 'ftp', 'tel', and more.
		 */
		$protocols = array_unique( (array) apply_filters( 'kses_allowed_protocols', $protocols ) );
	}

	return $protocols;
}

Hooks

apply_filters( ‘kses_allowed_protocols’, string[] $protocols )

Filters the list of protocols allowed in HTML attributes.

Changelog

Version Description
5.6.0 Added 'irc6' and 'ircs' to the protocols array.
5.3.0 Added 'sms' to the protocols array.
4.7.0 Added 'urn' to the protocols array.
4.3.0 Added 'webcal' to the protocols array.
3.3.0 Introduced.