shortcode_parse_atts()
Parses the shortcode arguments passed as a string.
The passed string must contain only arguments in the form of key="value", without the shortcode name and its brackets.
1 time — 0.000195 sec (fast) | 50000 times — 0.07 sec (speed of light)
No Hooks.
Returns
Array. A list of attributes and values as an array.
- Will return an empty array when
trim( $text ) == '""'. - Will return an empty string when
trim( $text ) == ''. - All other matches are checked via empty().
Usage
shortcode_parse_atts( $text );
- $text(string) (required)
- The string of shortcode attributes. For example:
module="WP" foo='bar'.
Examples
#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= */
#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. |
| Since 6.5.0 | The function now always returns an array, even if the original arguments string cannot be parsed or is empty. |