Despite your question is a generic PHP programming problem, what you’re trying to do can be achieved like so, where the key is the $i
which is a custom while
counter:
<div class="carousel-inner" role="listbox">
<?php if ( $popular_services->have_posts() ) :
$i = 0; // add this counter
while ( $popular_services->have_posts() ) : $popular_services->the_post();
?>
<?php if ( $i % 3 === 0 ) : ?>
<div class="carousel-item <?php if ( $popular_services->current_post == 0 ) : ?>active<?php endif; ?>">
<div class="row">
<?php endif; ?>
<div class="col-lg-4">
<div class="card">
your code here
</div>
</div>
<?php if ( $i % 3 === 2 ) : ?>
</div><!-- .row -->
</div><!-- .carousel-item -->
<?php endif; ?>
<?php $i++; // increment the counter
endwhile;
?>
<!-- This is needed if the (<number of posts> / 3) does not equal to 3. E.g. 11 posts would require 4 rows -->
<?php if ( $i % 3 !== 0 ) : ?>
</div><!-- .row -->
</div><!-- .carousel-item -->
<?php endif; ?>
<?php endif; // end have_posts() ?>
</div>
I hope that helps and you’re able to see the $i
parts and implement it properly in your code.