I’ve found others (source 1, source 2, source 3) using the following code for displaying a random gallery image (and it works) with the ACF Plugin:
<?php
$gallery = get_field('images');
$rand = array_rand($gallery, 1);
if( $gallery ): ?>
<img src="<?php echo $gallery[$rand]['sizes']['large']; ?>" alt="<?php echo $gallery[$rand]['alt']; ?>" />
<?php endif; ?>
But I’m trying to do it with wp_get_attachment_image()
(for responsive images) but not sure how to get the $rand
variable working? The ACF Documentation for the Gallery field has a 'Basic List of Images" example that uses wp_get_attachment_image()
but I'm not needing to loop through the gallery.
Any help would be greatly appreciated. I think it has to be something like the following, with the $rand
variable added somewhere:
<?php
$images = get_field('gallery');
$size = 'full'; // (thumbnail, medium, large, full or custom size)
$rand = array_rand($images, 1);
if( $images ): ?>
<?php echo wp_get_attachment_image( $images['ID'], $size ); ?>
<?php endif; ?>