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

    • November 2, 2016 at 9:30 am

    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.

    • dbrabyn

    • November 3, 2016 at 6:43 am

    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)

You must be logged in to reply to this topic.

We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.