Support

Account

Home Forums Add-ons Repeater Field Random Image Repeater

Solved

Random Image Repeater

  • Hello,

    I have a random image repeater working when i’m logged into my WordPress site – but not in any browser that i’m not logged into. Kicking myself to try and figure out what might be wrong in my setup:

    Tried the suggested “Get a random row from a repeater” here with my sub-field returning a value of an ID:

    <?php 
    
        $rows = get_field('home_hero' ); // get all the rows
        $rand_row = $rows[ array_rand( $rows ) ]; // get a random row
        $rand_row_image = $rand_row['image_set']; // get the sub field value 
    
        $image = wp_get_attachment_image_src( $rand_row_image, 'full' );
    
      ?>
        
    <div class="hero" style="background-image: url(<?php echo $image[0]; ?>);">
    

    …and tried a variation of the above with my sub-field returning a value of a URL:

    <?php 
    
        $rows = get_field('home_hero'); // get all the rows
        $rand_row = $rows[ array_rand( $rows ) ]; // get a random row
        $rand_row_image = $rand_row['image_set']; // get the sub field value 
    
     ?>
    
     <div class="hero" style="background-image: url(<?php echo $rand_row_image; ?>);">
    

    Both return an image from my image_set sub-field, but neither is random on refresh unless i’m logged in.

    Any help would be appreciated – thanks!

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

  • Thanks so much gummi! That was it. Bypassing the cache did the trick

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

The topic ‘Random Image Repeater’ is closed to new replies.