shortcode_atts()
Combine user attributes with known attributes and fill in defaults when needed.
The pairs should be considered to be all of the attributes which are supported by the caller and given as a list. The returned attributes will only contain the attributes in the $pairs list.
If the $atts list has unsupported attributes, then they will be ignored and removed from the final returned list.
Hooks from the function
Return
Array
. Combined and filtered attribute list.
Usage
shortcode_atts( $pairs, $atts, $shortcode );
- $pairs(array) (required)
- Entire list of supported attributes and their defaults.
- $atts(array) (required)
- User defined attributes in shortcode tag.
- $shortcode(string)
- The name of the shortcode, provided for context to enable filtering
Default: ''
Examples
#1 Adding a shortcode
Create a new shortcode [bartag]
that supports two attributes: foo
and bar
: [bartag foo="something" bar="something else"]
. Both attributes are optional and will take on default options if they are not provided.
add_shortcode( 'bartag', 'shortcode_callback' ); function shortcode_callback( $atts ) { $atts = shortcode_atts( [ 'foo' => 'no foo', 'bar' => 'default bar', ], $atts, 'bartag' ); return 'bartag: ' . esc_html( $atts['foo'] ) . ' ' . esc_html( $atts['bar'] ); } /* [bartag foo="koala" bar="bears"] outputs: bartag: koala bears [bartag foo=”koala”] outputs: bartag: koala default bar */
#2 Letter case of the array keys $pairs and $atts are important!
The case of the keys on the $pairs must match the keys on the $atts, or the value will be discarded.
See these examples:
print_r( shortcode_atts( [ 'CAPITAL' => '1', 'fooBar' => '2', ], [ 'CAPITAL' => '3', 'fooBar' => '4', ] ) ); // Output: Array ( [CAPITAL] => 3 [fooBar] => 4 ) print_r( shortcode_atts( [ 'CAPITAL' => '1', 'fooBar' => '2', ], [ 'capital' => '3', 'foobar' => '4', ] ) ); // Output: Array ( [CAPITAL] => 1 [fooBar] => 2 )
As we can see shortcode_atts() makes a case-sensitive comparison between the first argument (array of supported attributes and their defaults) and the second argument (array of user-defined attributes in shortcode tag). But the user-defined attributes are normalized to lowercase by WordPress before being passed to the shortcode callback function (see shortcode_parse_atts()).
So NEWER use UPPERCASE characters in keys of supported attributes!
So the correct variant for above code will be:
$atts = shortcode_atts( [ 'capital' => '1', 'foobar' => '2', ], $passed_atts );
Changelog
Since 2.5.0 | Introduced. |