It seems like this should be a common problem, but I can’t find the solution. Using a standard repeater custom field (title, image, link), I’m trying to create rotating banners that show one at a time, and randomly rotate.
I couldn’t correctly incorporate the “Get a random row from a repeater” code found here: https://www.advancedcustomfields.com/resources/repeater to work with my code found below. What is here renders all of the images at once.
Any help would be greatly appreciated.
<?php if( have_rows('title') ): ?>
<?php while( have_rows('title') ): the_row();
// vars
$image = get_sub_field('image');
$link = get_sub_field('link');
?>
<?php if( $link ): ?>
<a href="<?php echo $link; ?>">
<?php endif; ?>
<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt'] ?>" />
<?php if( $link ): ?>
</a>
<?php endif; ?>
<?php endwhile; ?>
<?php endif; ?>
I think you need to replace the while loop with
$rows = get_field('title' ); // get all the rows
$rand_row = $rows[ array_rand( $rows ) ]; // get a random row
and then use
$image = $rand_row['image' ];
$link = $rand_row['link' ];
to get the values.
Thanks for your response. I got some help, and here is the final code that we went with below. I’m not sure what the ’76’ does, but hope this helps others in the future.
<?php if( have_rows('title', 76) ): ?>
<?php
// Get the repeater field
$repeater = get_field( 'title', 76 );
// Get a random row.
$random_row = array_rand( $repeater, 1 );
// Get subfields
$image = $repeater[$random_row]['image'];
$link = $repeater[$random_row]['link'];
?>
<?php if( $link ): ?>
<a href="<?php echo $link; ?>">
<?php endif; ?>
<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt'] ?>" />
<?php if( $link ): ?>
</a>
<?php endif; ?>
<?php endif; ?>