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; ?>
    
    • 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:
    https://gist.github.com/airesvsg/2710de81f09613c456277ae3e38c2358

    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.