0

I am using this code so that users can input [photo no="1"], [photo no="2"], [photo no="3"] etc.. in their posts. However I heard that extract is an unsafe function to use. How could I modify this code to remove extract?

   function photo_shortcode($atts){
       extract(shortcode_atts(array(
          'no' => 1,
       ), $atts));
    
       $no     = is_numeric($no) ? (int) $no : 1;
       $images = get_field('fl_gallery');
    
      if ( !empty( $images ) ) {
       $image  = $images[$no];
       return ' $image['url'] ' ;
      }
    }
1

It's very simple: Just assign the value of shortcode_atts() (which is an array) to a variable and use it to access the shortcode attributes in the same way you access the items in any other arrays:

$atts = shortcode_atts( array(
    'no' => 1,
), $atts );

// Use $atts['no'] to get the value of the "no" attribute.
$no = is_numeric( $atts['no'] ) ? (int) $atts['no'] : 1;
0

extract brings variables from an array into local variables. It looks like in your case the only variable it does that with is $no, so you can replace extract with this code which will do the same thing:

Replace:

extract(shortcode_atts(array(
          'no' => 1,
       ), $atts));

with:

$arr = shortcode_atts(array(
          'no' => 1,
       ), $atts);

$no = $arr['no'];

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.