I am using Advanced Custom Fields to build a WordPress site. One of the pages needs to have a header image that changes randomly after a couple of seconds. I am trying to make it possible to choose which images will be randomly displayed with ACF.
With ACF I have created a custom field called Random images.
In the next step, the images will be loaded by the PHP template. Afterward, the images should be randomized with Javascript and shown on the page where I use the custom field. How do I do to make this work?
PHP & Javascript
<?php
if (get_row_layout() == 'random_images') {
?>
<section id="gallery">
<img src="' <?php get_sub_field('ra_photo_one'); ?>
<img src="' <?php get_sub_field('ra_photo_two'); ?>
<img src="' <?php get_sub_field('ra_photo_three'); ?>
<img src="' <?php get_sub_field('ra_photo_four'); ?>
<img src="' <?php get_sub_field('ra_photo_five'); ?>
</section>
<?php
}
?>
<script>
const getRandomNumber = (function() {
var nums = [1,2,3,4,5,6];
var current = [];
function rand(n) {
return (Math.random() * n)|0;
}
return function() {
if (!current.length) current = nums.slice();
return current.splice(rand(current.length), 1);
}
}());
const images = document.querySelectorAll('#gallery img');
getRandomImages = () => {
const imagesNums = [];
for (let i = 1; i < 7; i++) {
imagesNums.push(getRandomNumber());
}
images.forEach((img, index) => {
img.src = `./images/${imagesNums[index]}.jpg`
})
}
setInterval(() => {
getRandomImages()
}, 500);
</script
2
Answers
First, you have to create 1 empty section.
Now add all images to the javascript array.
Now add the random image logic.
and some CSS to smooth transition.
Check the working snippet below.
UPDATE
(as per OP’s request now the image will change automatically)
Based on your clarification that you want to show one image at a time, you could do the randomization in PHP, I think it will be easier:
That will choose a random image at load time and display it.
By the way, your snippet code forgot to include the
" />
closing part of eachimg
element, so I’ve added that here.It still wasn’t clear to me if you wanted to loop through the images with javascript randomly, so if you want that, you could do this:
Then you could go on to loop through on a timer in javascript showing one image at a time. You’ll need the proper CSS and Javascript functions to do that.