I'm using the following code to show images in an ACF Gallery field

<?php $images = get_field('gallery'); if( $images ): ?>

<?php foreach( $images as $image ): ?>

   <figure class="wp-caption aligncenter">

          <img class="b-lazy" src="<?php echo get_template_directory_uri(); ?>/assets/images/spinner.gif" data-src="<?php echo $image['sizes']['featured-720']; ?>" alt="<?php the_title();?>">


<?php endforeach; ?>
<?php endif; ?>

What i would like to do is to check for each $image, if there is another attached image with the same filename but different file extension (png).

For example:

There is an image attached called "ThisTitle.jpg" and I want to check if there is also another image attached called "ThisTitle.png"

I hope this make sense :)


You can use pathinfo() and getimagesize():

$info = pathinfo($image);

if ( @getimagesize($info['dirname'] . '/' . $info['filename'] . '.' . $extension_to_check) )
    // do something
| improve this answer | |
  • thanks for your reply. I don't know if i'm doing anything wrong, i just get this error: "Warning: pathinfo() expects parameter 1 to be string, array given in" – user2093301 Jun 10 '16 at 7:11
  • @user2093301 I think the error is very clear. I suggest to change $image to $image['sizes']['featured-720'] in your case. – SarahCoding Jun 10 '16 at 7:18
  • i think we are really close. I've change the code a bit to this: $info = pathinfo($image['sizes']['featured-720']); if ( getimagesize($info['dirname'] . '/' . $info['filename'] . '.jpg') ) { echo 'Exists'; } Now, if the image exists, it echoes the message, if not it gives the following error: Warning: getimagesize(domain/wp-content/uploads/2016/05/374/4_158602_2W1260.jpg): failed to open stream – user2093301 Jun 10 '16 at 8:00
  • @user2093301 We can use @ prefix to bypass that error, e.g @getimagesize(...). Note that if you only want to check against images inside your local folders, I recommend to use file_exits() as it's much more efficient in compare to getimagesize(). – SarahCoding Jun 10 '16 at 8:11

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.