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


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:

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

    Thanks in advance for any help.

  • I think I’ve got it!

    $images = get_field('header_image', 'option');
    $rand = array_rand($images, 1);
    if( $images ): ?>
    		<img src="<?php echo $images[$rand]['url']; ?>" alt="<?php echo $images[$rand]['alt']; ?>" />
    <?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:

    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.