Home › Forums › Add-ons › Repeater Field › Random repeater row – only show active › Reply To: Random repeater row – only show active
One way to do this would be to keep making selections until you find one that’s active
// add a counter
// this is an escape clause just in case no row is set to active
// because the following code with create an infinite loop if that happens
$escape_count = 0;
do {
$rand_row = $rows[ array_rand( $rows ) ]; // get a random row
$escape_count++;
} while (!$rand_row['active'] && $escape_count < 10);
The other way would be to loop through the array first and eliminate all the inactive ones first.
$rows = get_field( 'hero_blocks' ); // grab all rows from page ID
for ($i=0; $i<count($rows); $i++) {
if (!$rows[$i]['active']) {
unset($rows[$i]);
}
}
$rows = array_values($rows); // reindex the array
$rand_row = $rows[ array_rand( $rows ) ]; // get a random row
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.