函数文档

shortcode_parse_atts()

💡 云策文档标注

概述

shortcode_parse_atts() 函数用于从短代码标签中解析所有属性,返回一个以属性名为键、属性值为值的关联数组。该函数简化了属性检索过程,确保开发者能高效处理短代码参数。

关键要点

  • 函数接受一个字符串参数 $text,表示短代码的参数列表
  • 返回一个数组,键为属性名(小写),值为属性值;若无属性或解析失败,则返回空数组
  • 内部使用正则表达式 get_shortcode_atts_regex() 进行解析,并处理特殊字符和未闭合的 HTML 元素
  • 从 WordPress 2.5.0 版本引入,6.5.0 版本起始终返回数组,增强了稳定性

代码示例

$atts = shortcode_parse_atts( '[shortcode url="https://example.com" title="Example"]' );
echo $atts['url']; // 输出: https://example.com

注意事项

  • 属性名在返回数组中会被转换为小写,确保一致性
  • 函数会过滤掉未闭合的 HTML 元素,避免潜在的安全风险
  • 相关函数包括 get_shortcode_atts_regex(),用于获取解析属性的正则表达式

📄 原文内容

Retrieves all attributes from the shortcodes tag.

Description

The attributes list has the attribute name as the key and the value of the attribute as the value in the key/value pair. This allows for easier retrieval of the attributes, since all attributes have to be known.

Parameters

$textstringrequired
Shortcode arguments list.

Return

array Array of attribute values keyed by attribute name.
Returns empty array if there are no attributes or if the original arguments string cannot be parsed.

Source

function shortcode_parse_atts( $text ) {
	$atts    = array();
	$pattern = get_shortcode_atts_regex();
	$text    = preg_replace( "/[x{00a0}x{200b}]+/u", ' ', $text );
	if ( preg_match_all( $pattern, $text, $match, PREG_SET_ORDER ) ) {
		foreach ( $match as $m ) {
			if ( ! empty( $m[1] ) ) {
				$atts[ strtolower( $m[1] ) ] = stripcslashes( $m[2] );
			} elseif ( ! empty( $m[3] ) ) {
				$atts[ strtolower( $m[3] ) ] = stripcslashes( $m[4] );
			} elseif ( ! empty( $m[5] ) ) {
				$atts[ strtolower( $m[5] ) ] = stripcslashes( $m[6] );
			} elseif ( isset( $m[7] ) && strlen( $m[7] ) ) {
				$atts[] = stripcslashes( $m[7] );
			} elseif ( isset( $m[8] ) && strlen( $m[8] ) ) {
				$atts[] = stripcslashes( $m[8] );
			} elseif ( isset( $m[9] ) ) {
				$atts[] = stripcslashes( $m[9] );
			}
		}

		// Reject any unclosed HTML elements.
		foreach ( $atts as &$value ) {
			if ( str_contains( $value, '<' ) ) {
				if ( 1 !== preg_match( '/^[^<]*+(?:<[^>]*+>[^<]*+)*+$/', $value ) ) {
					$value = '';
				}
			}
		}
	}

	return $atts;
}

Changelog

Version Description
6.5.0 The function now always returns an array, even if the original arguments string cannot be parsed or is empty.
2.5.0 Introduced.

User Contributed Notes