shortcode_parse_atts()WP 2.5.0

Retrieve all attributes from the shortcodes tag.

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.

1 time — 0.000195 sec (fast) | 50000 times — 0.07 sec (speed of light)

No Hooks.

Return

Array|String. List of attribute values. Returns empty array if '""' === trim( $text ). Returns empty string if '' === trim( $text ). All other matches are checked for not empty().

Usage

shortcode_parse_atts( $text );
$text(string) (required)
-

Examples

0

#1 Demo

$res = shortcode_parse_atts( ' module="WP"    bar="" foo=\'bar\' baz bax=' );
print_r( $res );
/*
Array
	[module] => WP
	[bar]    => 
	[foo]    => bar
	[0]      => baz
	[1]      => bax=
*/
0

#2 Cut and break down the shortcode parameters

An example of how you can cut a shortcode parameter string and parse it into separate key=value

$str = <<<'STR'
	Content
	[five_element name="big badaboom" ident="multipassport" foo='bar']
	More Content
STR;

// for this check, the shortcode must be registered in WP, see: add_shortcode()
if( ! has_shortcode( $str, 'five_element' ) ){
	echo 'Shortcode not found';
}

preg_match( '~\[five_element(.+)\]~s', $str, $mm );

$res = shortcode_parse_atts( $mm[1] );

print_r( $res );

/*
Array
(
	[name]  => big badaboom
	[ident] => multipassport
	[foo]   => bar
)
*/

Changelog

Since 2.5.0 Introduced.

shortcode_parse_atts() code WP 6.1.1

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 ( false !== strpos( $value, '<' ) ) {
				if ( 1 !== preg_match( '/^[^<]*+(?:<[^>]*+>[^<]*+)*+$/', $value ) ) {
					$value = '';
				}
			}
		}
	} else {
		$atts = ltrim( $text );
	}

	return $atts;
}