0

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();?>">

   </figure>

<?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 :)

1 Answer 1

2

You can use pathinfo() and getimagesize():

$info = pathinfo($image);

if ( @getimagesize($info['dirname'] . '/' . $info['filename'] . '.' . $extension_to_check) )
{
    // do something
}
4
  • 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" Commented Jun 10, 2016 at 7:11
  • @user2093301 I think the error is very clear. I suggest to change $image to $image['sizes']['featured-720'] in your case.
    – Minh Tri
    Commented Jun 10, 2016 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 Commented Jun 10, 2016 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().
    – Minh Tri
    Commented Jun 10, 2016 at 8:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.