Create your gallery ACF field and make sure the return format is an Image Array.
Create a helper function in functions.php or preferably in a dedicated file imported via get_template_part('functions/load-random-image');
<?php
function render_random_images($images, $group = 'default') {
if (empty($images)) return;
foreach ($images as $index => $image) {
echo '<img src="' . esc_url($image['url']) . '" alt="' . esc_attr($image['alt']) . '" class="random-gallery-image" data-group="' . esc_attr($group) . '" style="display:none;">';
}
}
Use the function wherever needed:
<?php
$images = get_field('hero_images'); //replace hero_images with your field
?>
<?php if( $images ) : ?>
<?php render_random_images($images, 'hero'); ?>
<?php endif; ?>
export default function loadRandomImage() {
// Guard: if no random gallery on page
if(!document.querySelector(".random-gallery-image")) return;
const allImages = document.querySelectorAll('.random-gallery-image');
const groups = {};
allImages.forEach(img => {
const group = img.dataset.group || 'default';
if (!groups[group]) groups[group] = [];
groups[group].push(img);
});
Object.values(groups).forEach(images => {
const randomIndex = Math.floor(Math.random() * images.length);
images.forEach((img, index) => {
img.style.display = index === randomIndex ? 'block' : 'none';
});
});
}
If using the barba.js library, add the loadRandomImage() function to the page-transition.js file:
import loadRandomImage from './loadRandomImage';
And invoke the function in the afterEnter hook:
barba.hooks.afterEnter(() => {
// Wait until new content is fully in DOM
requestAnimationFrame(() => {
// ...your other functions
loadRandomImage();
});
});
If not using the barba.js library, add the function in your main.js file:
import loadRandomImage from './loadRandomImage';
window.addEventListener("DOMContentLoaded", () => {
// ...your other functions
loadRandomImage();
});
Make sure you do not invoke the function in both page-transition.js and main.js as this will have some undesired results.
This method is modular and re-usable. It will also work despite cache restrictions.