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'] ' ;
}
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 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;
Method 2
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'];
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0