PHP: Randomise ACF Repeater Row That’s Displayed

We needed to display an advert on a website, however, the client wanted the adverts to change based on a pool of adverts. We achieved this by counting the repeater rows and then picking a random number from 1 to the current row count and displayed the content.

<?php $sidebarAdverts = get_field('REPEATER_ROW_NAME', 'options');

if( have_rows('REPEATER_ROW_NAME', 'options') ):
	$countAdverts = count($sidebarAdverts);
	$chosenNumber = rand(1, $countAdverts);

	while( have_rows('REPEATER_ROW_NAME', 'options') ) : the_row();
		$currentAdvert = get_row_index();

		if($currentAdvert == $chosenNumber):
			$advertImage = get_sub_field('upload_image');
			$advertLink = get_sub_field('link_to');?>
			<a href="<?php echo esc_url($advertLink);?>" title="<?php echo esc_attr($advertImage['alt']);?>">
				<img src="<?php echo esc_url($advertImage['url']);?>" alt="<?php echo esc_attr($advertImage['alt']);?>">
			</a>
		<?php endif;

	endwhile;
endif;?>

Click here to download the ACF import file for the fields used in this example.

Powered by BetterDocs