1

The WordPress developers reference page for shortcode_atts() states:

$atts (array) (Required) User defined attributes in shortcode tag.

But I do not understand this definition.

For example, in this piece of the WP Frontend Profile plugin:

$atts = shortcode_atts(
     [
     'role' => '',
     ],
     $atts
);

As far as I understand, shortcode_atts() is used to create a map between the shortcode attributes and a PHP array.

But I don't see what the purpose of the $atts parameter is.

3

When a user writes a shortcode:

[my_shortcode att1="Attribute 1 value" att2="Attribute 2 value"]

The attributes are passed to the shortcode's callback function as an array as the first argument:

function my_shortcode_callback( $atts ) {
    // $atts = array(
    //  'att1' => 'Attribute 1 value',
    //  'att2' => 'Attribute 2 value',
    // );
}
add_shortcode( 'my_shortcode', 'my_shortcode_callback' );

The function shortcode_atts():

Combine user attributes with known attributes and fill in defaults when needed.

So you use shortcode_atts() to create an array with default values all supported attributes, except for any that were provided by the user. To do this you pass an array of all supported attributes and their defaults as the first argument, and the user-provided attributes as the second argument. The second argument will therefore be the same array that is passed to the callback function:

function my_shortcode_callback( $user_atts ) {
    // $user_atts = array(
    //  'att1' => 'Attribute 1 value',
    //  'att2' => 'Attribute 2 value',
    // );

    $default_atts = array(
        'att1' => 'Attribute 1 default',
        'att2' => 'Attribute 2 default',
        'att3' => 'Attribute 3 default',
    );

    $atts = shortcode_atts( $default_atts, $user_atts, 'my_shortcode' );

    // $atts = array(
    //  'att1' => 'Attribute 1 value',
    //  'att2' => 'Attribute 2 value',
    //  'att3' => 'Attribute 3 default',
    // );
}
add_shortcode( 'my_shortcode', 'my_shortcode_callback' );

You do this so that you can do things like use $atts['att3'] without causing a PHP error if the user did not enter att3="Attribute 3 value" when placing the shortcode.

The 3rd argument of shorcode_atts() should be set to the shortcode name. This makes it possible to filter the shortcode attributes like this:

add_filter(
    'shortcode_atts_my_shortcode',
    function( $atts ) {
         $atts['atts2'] = 'Attribute 2 override';

         return $atts;
    }
);
1
  • Beyond Awesome. Thank you a million times. May 22 '20 at 10:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.