How to display a random gallery image with ACF

To display a random image, from a gallery, we are going to use the Gallery field type from ACF and some custom PHP code.

Step 1

With ACF, let's add a new Field Group and then a Gallery Field Type. We can keep everything else by default:

acf-gallery-settings

Step 2

We need to add some image to our post, obviously!

Step 3

Finally we add a Code Block element where we want to display the image, and paste the following PHP code;

<?php
$images = get_field('gallery', '', false); // Adding the `false` parameter returns raw/unformatted value
$size = 'full'; // (thumbnail, medium, large, full or custom size)
$rand = array_rand($images ?? [null]);
$attr = ["class" => "random-image","alt"=>"random image","loading"=>"lazy"];

if( $images ): ?>
<?php echo wp_get_attachment_image( $images[$rand], $size, "", $attr ); ?>
<?php endif; ?>

Now, every time the page loads (frontend or backend), one of the images from the gallery will show up randomly.

We can style de Code Block (which is the container) or directly the image via the custom class we have added:

note

Be sure to check the $attr variable, as it contain the image markup. You can add your own class, alt, or even set the lazy loading.

more info : https://developer.wordpress.org/reference/functions/wp_get_attachment_image/