I recently had a client that wanted a random image to display in a Bootstrap modal popup banner on their website.

The banner content was created with an Advanced Custom Fields image field for easy editing, with a text field as well.

To change the static banner image to a randomized image, I just created a repeater field where the image field was, added an image field into the repeater (using the Image URL return value), then set up the code like this:


<?php 
$repeater = get_field( 'repeater_field_name'); //get the repeater field
$rand = rand(0, (count($repeater) - 1));&nbsp; //randomize the rows
$message = get_field('text_field');
?>

<div class="modal" id="modal-content" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<img src="<?php echo $repeater[$rand]['image_sub_field'];?>" style="width:80%;height:auto;" id="stopimg">
<span><p><?php echo $message; ?></p>
</span>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Acknowledged</button>
</div>
</div>
</div>
</div>

Thanks to bridgetwes for the randomized row code on github.

Leave a Comment

Your email address will not be published. Required fields are marked *