admin管理员组

文章数量:1327073

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'] ' ;
      }
    }

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'] ' ;
      }
    }
Share Improve this question asked Aug 4, 2020 at 16:15 JoaMikaJoaMika 6986 gold badges27 silver badges58 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 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;

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'];

本文标签: phpRemove extract from function