Home › Forums › Add-ons › Repeater Field › 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
The topic ‘Random Image Repeater’ is closed to new replies.
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.