Problem with extract() with custom shortcode

If no attributes are used on the shortcode, then $atts will be a string, so you can’t use extract on it. Part of your problem is that you’re not using shortcode_atts correctly. You need to assign the value of shortcode_atts back to $atts. That will ensure that $atts is an array with all the correct keys.

add_shortcode('img_portfolio', 'add_img_portfolio');

function add_img_portfolio($atts){
    $atts = shortcode_atts(array(
      'url' => 'https://s3.amazonaws.com/popco/images/services/starter-page/img-placeholder.jpg',
      'height' => 'auto'
    ), $atts);
    extract($atts);
    return '<img class="img-fluid d-block mx-auto" src="'.$url.'" alt="" width=100% height="'.$height.'">';
}

But honestly, don’t use extract(), it’s considered a bad practice, because your code ends up with a bunch of variables that aren’t apparently assigned anywhere. Just use $atts as an array:

function add_img_portfolio($atts){
    $atts = shortcode_atts(array(
      'url' => 'https://s3.amazonaws.com/popco/images/services/starter-page/img-placeholder.jpg',
      'height' => 'auto'
    ), $atts);

    return '<img class="img-fluid d-block mx-auto" src="'.$atts['url'].'" alt="" width=100% height="'.$atts['height'].'">';
}

Leave a Comment