Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

193
Views
How to randomize images in WordPress with Javascript (Advanced custom fields)

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.ACF

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


about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

First, you have to create 1 empty section.

<section id="gallery"></section>

Now add all images to the javascript array.

<script>
var images = [
    '<?php get_sub_field('ra_photo_one'); ?>',
    '<?php get_sub_field('ra_photo_two'); ?>',
    '<?php get_sub_field('ra_photo_three'); ?>',
    '<?php get_sub_field('ra_photo_four'); ?>',
    '<?php get_sub_field('ra_photo_five'); ?>'
];
</script>

Now add the random image logic.

setInterval(function(){
    $('#gallery').html('<img class="fade-in" src="' + images[Math.floor(Math.random() * images.length)] + '">');
}, 3000);

and some CSS to smooth transition.

.fade-in{
  -webkit-animation: fade-in 2s ease;
  -moz-animation: fade-in ease-in-out 2s both;
  -ms-animation: fade-in ease-in-out 2s both;
  -o-animation: fade-in ease-in-out 2s both;
  animation: fade-in 2s ease;
  visibility: visible;
  -webkit-backface-visibility: hidden;
}

@-webkit-keyframes fade-in{0%{opacity:0;} 100%{opacity:1;}}
@-moz-keyframes fade-in{0%{opacity:0} 100%{opacity:1}}
@-o-keyframes fade-in{0%{opacity:0} 100%{opacity:1}}
@keyframes fade-in{0%{opacity:0} 100%{opacity:1}}

Check the working snippet below.

UPDATE (as per OP's request now the image will change automatically)

var images = [
    'https://via.placeholder.com/150?text=123',
    'https://via.placeholder.com/150?text=456',
    'https://via.placeholder.com/150?text=789',
    'https://via.placeholder.com/150?text=ABC',
    'https://via.placeholder.com/150?text=PQR',
];

$('#gallery').html('<img class="fade-in" src="' + images[Math.floor(Math.random() * images.length)] + '">');

setInterval(function(){
    $('#gallery').html('<img class="fade-in" src="' + images[Math.floor(Math.random() * images.length)] + '">');
}, 3000);
.fade-in{
  -webkit-animation: fade-in 2s ease;
  -moz-animation: fade-in ease-in-out 2s both;
  -ms-animation: fade-in ease-in-out 2s both;
  -o-animation: fade-in ease-in-out 2s both;
  animation: fade-in 2s ease;
  visibility: visible;
  -webkit-backface-visibility: hidden;
}

@-webkit-keyframes fade-in{0%{opacity:0;} 100%{opacity:1;}}
@-moz-keyframes fade-in{0%{opacity:0} 100%{opacity:1}}
@-o-keyframes fade-in{0%{opacity:0} 100%{opacity:1}}
@keyframes fade-in{0%{opacity:0} 100%{opacity:1}}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section id="gallery"></section>

about 4 years ago · Juan Pablo Isaza Report

0

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:

<?php
if (get_row_layout() == 'random_images') {
    $field_names = ['one', 'two', 'three', 'four', 'five'];
    shuffle($field_names); // this randomizes that array
    $name = $field_names[0];
?>
    <section id="gallery">
    <img src="' <?php get_sub_field('ra_photo_' . $name); ?>" />
    </section>
    <?php
}
?>

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 each img 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:

<?php
if (get_row_layout() == 'random_images') {
    $field_names = ['one', 'two', 'three', 'four', 'five'];
    shuffle($field_names); // this randomizes that array
?>
    <section id="gallery">
    <?php foreach ($field_names as $field) { ?>
        <img style="display: none;" src="' <?php get_sub_field('ra_photo_' . $field); ?>" />
    <?php } ?>
    </section>
    <?php
}
?>

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!