Support

Account

Home Forums Add-ons Repeater Field Random Image Repeater Reply To: Random Image Repeater

  • Do you have caching plugin on your site or your hosting? If you have caching, then it’ll serve the static cache file directly without running through your php code. You might want to consider using js to do the randomization in that case.

    Something like:

    
    <?php
        $availableImages = [];
    
        while (have_rows('repeater_field_name')): the_row();
            $availableImages[] = wp_get_attachment_image_url(get_sub_field('sub_field_name', 'full'));
        endwhile;
    ?>
    
    <script>
        var availableImages = <?php echo json_encode($$availableImages); ?>;
    
        jQuery(function($) {
            var randomImage = availableImages[Math.floor(Math.random() * availableImages.length)];
            $('.hero').css('background-image', 'url(' + randomImage + ')');
        });
    </script>
    

    Cheers.