Creating a loop of Bootstrap Modals

To create a loop of Bootstrap style modals on a page, you can use a foreach or while loop in PHP.

First, let’s do the code for one modal.

Single Modal Code

<!-- Button to Open the Modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal"> Open modal </button>
<!-- The Modal -->
<div class="modal" id="myModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <!-- Modal Header -->
            <div class="modal-header">
                <h4 class="modal-title">Modal Heading</h4>
                <button type="button" class="close" data-dismiss="modal">×</button>
            </div>
            <!-- Modal body -->
            <div class="modal-body"> Modal body.. </div>
            <!-- Modal footer -->
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

A foreach loop of modals

<?php
$modals = array( 'modal1', 'modal2', 'modal3', 'modal4' );// Set the array
$i = 1; // Set the increment variable
foreach( $modals as $modal ):
?>
<!-- Button to Open the Modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal-<?php echo $i; // Displaying the increment ?>">
Open modal <?php echo $i;?>
</button>
<!-- The Modal -->
<div class="modal" id="myModal-<?php echo $i; // Displaying the increment ?>">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Modal Heading</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
I am <?php echo $modal; // Displaying the modal name ?>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<?php $i++; // Increment the increment variable
endforeach; //End the loop ?>

So an array is created with a known amount of modals, a counter variable $i is created and incremented after each loop iteration, that counter variable is used in the button and modal ID to link the correct modals together.

See how to create a WordPress custom loop of modals.

2 comments

Leave your comment