Home Forums Add-ons Gallery Field Select only images from gallery with custom meta field


Select only images from gallery with custom meta field

  • Hi there – I’m sure this has a really easy answer, but I’m just completely missing a step. I’m trying to display the first five images from a gallery that are checked “featured” using a custom meta attachment field.

    I can display the featured images from the gallery in total, but when I try to limit it to five I’m definitely using my counter incorrectly – the loop is counting the first five images and then displaying only those that are featured from the first five, instead of from the whole gallery.

    I know that this is what I’m trying to do: I want to get all the images from the gallery, then go through that array of images and get only the ones marked featured, then only display the first five of those. Any help with this would be much appreciated and thank you so much for reading. My code is below:

    $images = get_field('image_gallery', 'option');
    if( $images ): ?>
    $i = 0;
    foreach( $images as $image ): 
    $featured = get_field('feature_this_image', $image['id']);
    if ($featured && $i <= 4 ) { ?>
    <div class="gallery-image">
    <a href="<?php echo $image['url']; ?>"><img src="<?php echo $image['sizes']['gallery-thumb']; ?>" alt="<?php echo $image['alt']; ?>" /></a>
    <?php } $i++; endforeach; ?>
    <?php endif; ?>
  • if we are lucky it works when you change this line
    <?php $i++; } endforeach; ?>
    the counter should only go up when image is featured,
    thats why it should be inside the featured loop and not outside like you have it now

  • Hi and thank you – that totally did the trick. I had looked at the code for so long I was just missing that one tiny thing, yikes.

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘Select only images from gallery with custom meta field’ is closed to new replies.