Home › Forums › Add-ons › Repeater Field › Random 3 Rows of repeater field
Hello. I need to retreive 3 RANDOM rows from a Repeater field with more than 3 rows, is that possible?
Thanks in advanced
Daniel
The following code should help you achieve that
<?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, 3 );
// 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/>';
}
?>
Let me know if this helps.
Based on your resource page for displaying a random row, the code for doing this has changed to the following. I tried the code above and it didn’t work, but the code stated on the resource page does work to display a random row perfectly. My question now is how to mod it to display a random set of rows, not just one. Note, I tried adding that comma and a number that’s in your example, but it broke the whole output and displays nothing.
<?php
$rows = get_field('repeater_field_name' ); // get all the rows
$rand_row = $rows[ array_rand( $rows ) ]; // get a random row
$rand_row_image = $rand_row['sub_field_name' ]; // get the sub field value
// Note
// $first_row_image = 123 (image ID)
$image = wp_get_attachment_image_src( $rand_row_image, 'full' );
// url = $image[0];
// width = $image[1];
// height = $image[2];
?>
<img src="<?php echo $image[0]; ?>" />
The topic ‘Random 3 Rows of repeater field’ 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.