Close/Open Div After Loop has Ran 3 Times

I have a loop that creates columns inside of a .row div. After the loop has ran 3 times, I would like those columns to be wrapped in a “row” div and a new “row” div to be created for the next set of 3 columns.

Here is the loop:

Read More
<div class="row">
  <?php if( have_rows('content_modules') ): ?>
    <?php while( have_rows('content_modules') ): the_row(); 
        $photo = get_sub_field('module_photo');
        $title = get_sub_field('module_title');
        $content = get_sub_field('module_content'); ?>

    <div class="columns">
        <img src="<?php echo $photo ?>" />          
        <h3><?php echo $title ?></h3>
        <?php echo $content ?>
    </div>

  <?php endwhile; endif;?>
</div>

This loop runs great, however, I can’t seem to wrap each set of 3 columns inside of a row.

Related posts

Leave a Reply

1 comment

  1. Use modulo to determine whether you should start a new row or not.

    <?php if( have_rows('content_modules') ): ?>
        <?php
        $i = 0;
        while( have_rows('content_modules') ): the_row();
    
        $photo = get_sub_field('module_photo');
        $title = get_sub_field('module_title');
        $content = get_sub_field('module_content');
        ?>
    
            <?php if($i % 3 == 0): ?>
                <div class="row">
            <?php endif; ?>
    
            <div class="columns">
                <img src="<?php echo $photo ?>" />          
                <h3><?php echo $title ?></h3>
                <?php echo $content ?>
            </div>
    
            <?php if($i % 3 == 2): ?>
                </div>
            <?php endif; ?>
    
        <?php $i++; endwhile; endif;?>
    <?php endif; ?>