I am using this code as part of a function:
function photo_shortcode($atts){
extract(shortcode_atts(array(
'no' => 1,
), $atts));
$no = is_numeric($no) ? (int) $no : 1;
$images = get_field('fl_gallery');
$image = $images[$no];
}
fl_gallery
is an ACF gallery field. However, sometimes I am getting PHP Notice: Undefined offset: 1,2,3 etc.. on line $image = $images[$no];
Why would this be happening and how to fix it?
I am using this code as part of a function:
function photo_shortcode($atts){
extract(shortcode_atts(array(
'no' => 1,
), $atts));
$no = is_numeric($no) ? (int) $no : 1;
$images = get_field('fl_gallery');
$image = $images[$no];
}
fl_gallery
is an ACF gallery field. However, sometimes I am getting PHP Notice: Undefined offset: 1,2,3 etc.. on line $image = $images[$no];
Why would this be happening and how to fix it?
Share Improve this question edited Jul 31, 2020 at 10:07 JoaMika asked Jul 31, 2020 at 10:05 JoaMikaJoaMika 6986 gold badges27 silver badges58 bronze badges 4 |1 Answer
Reset to default 1You assumed get_field
would always return images, but what if there are no images to return?
$images = get_field('fl_gallery');
$image = $images[$no];
The code never checks $images
to see if it's empty, or an error value.
On top of that, what if it returned images, but it returned 3 images, and $no
is 4? You can't access something that doesn't exist without warnings, you have to check first. This is why you're getting PHP warnings.
For example:
if ( empty( $images ) ) {
// no images!
}
if ( empty( $images[$no] ) ) {
// that image doesn't exist
}
However, you're using get_field
which is an ACF API, not a WordPress API. You will need to consult the ACF documentation on what that function does when it encounters problems, and how to handle the error. It may not return an array at all but final HTML.
You'll also want to add more validation. For example [photo_shortcode no=9000]
or [photo_shortcodo no="-1"]
or [photo_shortcode no="0.5"]
are all numeric and would generate those PHP warnings
Sidenote: extract
reduces security, makes code unreadable by machines and tools, and can overwrite variables unexpectedly enabling security holes and bugs. Never use it.
$no
? And what does the value of$images
look like? – Jacob Peattie Commented Jul 31, 2020 at 10:07extract
, I also see your shortcode doesn't return anything, and you never check ifget_field
worked or not, you're just assuming it worked. What if there is n gallery? Or yoour shortcode runs before a post is set as the current post? Or on a 404 page? Clearly it didn't work and the code just carried on anyway, resulting in the PHP notices – Tom J Nowell ♦ Commented Jul 31, 2020 at 10:21