简体   繁体   中英

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; ?>

Assuming your code snippet worked (but lacks the random element), you could do something like the following.

<?php 
$images = get_field('project_documentation', 'option');

if( $images ) {
        $featured_images = array();
        foreach( $images as $image ) {
                $featured = get_field('featured_image', $image['id']);

                if ($featured == '1' ) {
                        $featured_images[] = $image;
                }
        }

        if ( !empty( $featured_images ) ) {
                $rand = rand(0, count( $featured_images ));
                $image = $featured_images[$rand];
                ?>
                <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
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM