samedi 17 septembre 2022

Display image from ACF gallery only if it has meta field

I have an ACF image gallery and have set up a True / False (1/0) custom field to image attachments named "featured_image". Inside the gallery, several images are selected as the featured image while others are not.

What I would like to achieve is to randomly select one of the images which has the "featured_image" custom field as true.

My code thus far is included below, however I cannot get it to work by selecting only images from the gallery marked as "featured_image", or know how to make the selection random. Help is appreciated!

        <?php 
        $images = get_field('project_documentation', 'option');
        
        if( $images ): ?>
        <?php 
        $i = 0;
        foreach( $images as $image ): 
        $featured = get_field('featured_image', $image['id']);
        
        if ($featured == '1' ) { ?>
        
        <div class="gallery-image">
        <a href="<?php echo $image['url']; ?>"><img src="<?php echo $image['sizes']['large']; ?>" alt="<?php echo $image['alt']; ?>" /></a>
        </div>
        
        <?php } $i++; endforeach; ?>
        <?php endif; ?>



Aucun commentaire:

Enregistrer un commentaire