Hi there I am showing a random repeater row on the front end, but would love the ability to only show a random row that also has an active sub field (true/false). Is this possible? Many thanks
<?php
$rows = get_field( 'hero_blocks' ); // grab all rows from page ID
$rand_row = $rows[ array_rand( $rows ) ]; // get a random row
$rand_row_image = $rand_row['hero_image' ]; // get the sub field value
$image = wp_get_attachment_image_src( $rand_row_image, 'featured_image' );
$caption = $rand_row['caption'];
$subtitle = $rand_row['subtitle'];
$buttonLink = $rand_row['button_link'];
$buttonText = $rand_row['button_text'];
?>
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
Thanks John this is perfect!