0

I'm trying to add an image with this shortcode:

add_shortcode('img_portfolio', 'add_img_portfolio');

function add_img_portfolio($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.'">';
  }

And getting this error:

Warning: extract() expects parameter 1 to be array, string given

Knowing that this same function pattern works in another shortcode i've made.

Thanks

1
  • You should avoid using extract for security/readability/usability reasons
    – Tom J Nowell
    Aug 31, 2017 at 13:02

1 Answer 1

3

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'].'">';
}
2
  • 1
    Thanks for your help and the advice it works perfectly now!
    – Zac
    Aug 31, 2017 at 13:05
  • ps: we should also remember to escape these attributes in the output
    – birgire
    Aug 31, 2017 at 13:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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