Salih K Salih K - 5 months ago 11
PHP Question

PHP Loop - Add a Div around every three Items

Here is the Code that works for 3 items, and if there is exact multiples of 3 items (ie, if we have 9 items) then it will add an extra blank div at the end. if there is items that is not multiples of 3 (ie, if we have 8 items) then it works fine. I am not a programmer, so any help will be appreciated: the Code Sample --->

<div class="row">
<?php
$i = 1;
$wp_query = new WP_Query( array( 'posts_per_page' => -1,
'post_type' => 'projects' ) );
echo '<div class="panel">';
if ( $wp_query->have_posts() ) :
while ( $wp_query->have_posts() ) : $wp_query->the_post();
the_title();
if($i % 3 == 0) { echo '</div><div class="panel">'; }
$i++;
endwhile; endif;
echo '</div>';
?>

</div>

Answer

Try this code

<div class="row">
    <?php 
      $i = 1;
      $wp_query = new WP_Query( array( 'posts_per_page' => -1, 
                  'post_type' => 'projects' ) );

      if ( $wp_query->have_posts() ) : 
         while ( $wp_query->have_posts() ) :
            if($i % 3 == 1) { echo '<div class="panel">'; }
            $wp_query->the_post();
            the_title();         
            if($i % 3 == 0 || $i == $wp_query->post_count) { echo '</div>'; }
            $i++; 
         endwhile;
      endif; 
  ?>

</div>