Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Return a random row of data from an ACF repeater field
<?php
// Get the repeater field
$repeater = get_field( 'repeater_field_name' );
// Get a random rows. Change the second parameter in array_rand() to how many rows you want.
$random_rows = array_rand( $repeater, 2 );
// Loop through the random rows if more than one is returned
if( is_array( $random_rows ) ){
foreach( $random_rows as $random_row ){
// Output data here. Replace sub field names.
echo 'Sub Field 1: ' . $repeater[$random_row]['sub_field_1'] . '<br/>';
echo 'Sub Field 2: ' . $repeater[$random_row]['sub_field_2'] . '<br/><br/>';
}
} else {
// Output data here. Replace sub field names.
echo 'Sub Field 1: ' . $repeater[$random_rows]['sub_field_1'] . '<br/>';
echo 'Sub Field 2: ' . $repeater[$random_rows]['sub_field_2'] . '<br/><br/>';
}
?>
@bridgetwes

This comment has been minimized.

Copy link

commented Jul 18, 2013

Thanks for the tip!

If you only want one random item from ACF repeater, you can also do:

$repeater = get_field( 'repeater_field_name' );
$rand = rand(0, (count($repeater) - 1));
echo $repeater[$rand]['sub_field_1'];
@IntrepidRealist

This comment has been minimized.

Copy link

commented Mar 13, 2014

Bridgetwes,
You saved my a$$! Thank you!

@psorensen

This comment has been minimized.

Copy link

commented Jun 10, 2014

Thanks!

@davemac

This comment has been minimized.

Copy link

commented May 11, 2016

I had an issue with the rows not being random in PHP 5.6, by using shuffle() it solved the issue http://stackoverflow.com/questions/20163709/php-array-rand-not-working-properly-when-randomizing-more-then-1-random-arraykey

@csaborio001

This comment has been minimized.

Copy link

commented Jul 30, 2018

Sweet - thank you!

@doopsi

This comment has been minimized.

Copy link

commented Feb 13, 2019

Thanks for the tip!

If you only want one random item from ACF repeater, you can also do:

$repeater = get_field( 'repeater_field_name' );
$rand = rand(0, (count($repeater) - 1));
echo $repeater[$rand]['sub_field_1'];

Thanks!

@PaulBart

This comment has been minimized.

Copy link

commented May 8, 2019

Great thanks! I'm trying to get a version that will also "reload" the 3 random rows I had displayed every few seconds?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.