Home › Forums › Front-end Issues › How to randomize images in WordPress with jQuery or Javascript?
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 (setInterval). 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 jQuery or Javascript and shown, one at a time, on the page where I use the custom field. How do I do to make this work? Now the images aren’t displayed.
PHP & jQuery
if (get_row_layout() == 'random_images') {
echo '<section id="gallery"></section>';
?>
<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'); ?>'
];
$('#gallery').html('<img class="fade-in" src="' + images[Math.floor(Math.random() * images.length)] + '">');
setInterval(function() {
$('<img class="fade-in" src="' + images[Math.floor(Math.random() * images.length)] + '">').appendTo('#gallery');
}, 3000);
</script>
<?php
}
CSS
.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}}
I have registered jQuery in functions.php, but I am not sure if I have done it correctly.
functions.php
wp_register_script( 'jQuery', 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js', null, null, true );
wp_enqueue_script('jQuery');
Can you give more information on what is not working? Are there errors?
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.