Support

Account

Home Forums Add-ons Gallery Field Random image from Gallery field

Solving

Random image from Gallery field

  • I have set up a Gallery field in the Options section which includes 5 images. I then have an image header on my site where I want to grab a single random image from that gallery field. Is that possible? If so, could anybody guide me. At the moment I use the following code to display all images in a gallery field:

    
    <?php 
    
    $images = get_field('header_image', 'option');
    
    if( $images ): ?>
        <ul>
            <?php foreach( $images as $image ): ?>
                <li>
                    <a href="<?php echo $image['url']; ?>">
                         <img src="<?php echo $image['sizes']['thumbnail']; ?>" alt="<?php echo $image['alt']; ?>" />
                    </a>
                </li>
            <?php endforeach; ?>
        </ul>
    <?php endif; ?>
    

    Thanks in advance for any help.

  • I think I’ve got it!

    
    <?php 
    	
    $images = get_field('header_image', 'option');
    $rand = array_rand($images, 1);
    	
    if( $images ): ?>
    	<div>
    		<img src="<?php echo $images[$rand]['url']; ?>" alt="<?php echo $images[$rand]['alt']; ?>" />
    	</div>
    <?php endif; ?>
    
  • I presume you cache your pages. How do you get past the cache so that the header images changes upon refresh?

  • Unfortunately that’s the problem with anything random. I have my caching plugin clear the cache once an hour so obviously not ideal at least it’s random 24 times a day 😉

    If you can figure something out I’d be interested to hear how you did it.

  • WP Rest-API and Ajax is apparently a solution.

    Someone kindly put this together for me:
    https://gist.github.com/airesvsg/2710de81f09613c456277ae3e38c2358

    Haven’t tested it yet.

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

The topic ‘Random image from Gallery field’ is closed to new replies.