Support

Account

Home Forums ACF PRO Wrap every 3 items, add div after these, then repeat

Helping

Wrap every 3 items, add div after these, then repeat

  • I want to wrap every 3 items and add a div (.popup) after these, then continue with the other rows and repeat the same.
    This has to the output:

    <div class=”container”>
    <div class=”row”>
    <div class=”item”>name1</div>
    <div class=”item”>name2</div>
    <div class=”item”>name3</div>
    </div>
    <div class=”popup”>
    <div class=”item”>name1</div>
    <div class=”item”>name2</div>
    <div class=”item”>name3</div>
    </div>
    <div class=”row”>
    <div class=”item”>name4</div>
    <div class=”item”>name5</div>
    <div class=”item”>name6</div>
    </div>
    <div class=”popup”>
    <div class=”item”>name4</div>
    <div class=”item”>name5</div>
    <div class=”item”>name6</div>
    </div>
    <div class=”row”>
    <div class=”item”>name7</div>
    <div class=”item”>name8</div>
    <div class=”item”>name9</div>
    </div>
    <div class=”popup”>
    <div class=”item”>name7</div>
    <div class=”item”>name8</div>
    <div class=”item”>name9</div>
    </div>
    </div>

    this is what i have tried:

    <?php
    if (have_rows(‘content’)) {
    $count = 0;
    while (have_rows(‘content’)) {
    if ($count > 0 && ($count % 3 == 0)) {
    // after first itteration
    // close li and open a new one every 3 rows
    ?>
    </div>
    <div class=”container”>
    <?php the_sub_field(‘name’); ?>
    </div>
    <div class=”row”>
    <?php
    }
    the_row();
    ?>
    <div class=”item”><?php the_sub_field(‘name’); ?></div>
    <?php
    reset_rows();
    $count++;
    }
    } else {
    } ?>
    </div>

    But I have not managed to do it, I would appreciate your help to solve it

  • You should first store every 3 items to an array. Each value has 3 items. Then iterate the array to output row and popup.
    Also you should keep ‘container’ out of loop.

    <?php
    $items = [];
    if ( have_rows( 'content' ) ):
    	while ( have_rows( 'content' ) ): the_row();
    		//initiate if is not set
    		$items[ get_row_index() % 3 ] = $items[ get_row_index() % 3 ] ? $items[ get_row_index() % 3 ] : '';
    		$items[ get_row_index() % 3 ] .= '<div class="item">' . get_sub_field( 'name' ) . '</div>';
    	endwhile;
    endif;
    ?>
    <div class="container">
    	<?php foreach ( $items as $item ) {
    		echo '<div class="row">';
    		echo $item;
    		echo '</div>';
    		echo '<div class="popup">';
    		echo $item;
    		echo '</div>';
    	}
    	?>
    </div>
Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.