Support

Account

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