Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

198
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda