Support

Account

Home Forums Front-end Issues How to randomize images in WordPress with jQuery or Javascript?

Solving

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.

    custom fields

    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?

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.