Unclosed div when wrapping every 2 divs in a loop

I have the following set up below. I’m trying to wrap ever 2 divs in a “row”.

When its an even number it works great, but when there’s an odd number, I end with an open div and get html errors. Any ideas on how to better make sure there is a closing div would be appreciated

<?php

            $args = array(            
              'post_type' => 'portfolio-project',
              'posts_per_page' => -1, 
              'orderby' => 'menu_order',
              'order' => 'ASC'
            );

            $query = query_posts($args);

        ?>

        <?php $i=1; ?>

        <?php while (have_posts()) : the_post(); ?>
            <?php if($i==1 || $i%2==1) echo '<div class="row">' ;?>

            <div class="col-sm-6">
                <?php the_title();?>
            </div>

            <?php if($i%2==0) echo '</div>' ; ?>

        <?php $i++; endwhile; wp_reset_query();?>

Related posts

Leave a Reply

4 comments

  1. You have to put and end close tag if needed. I change the counting method to be more clear.

        <?php $i=1;  while (have_posts()) : the_post(); ?>
            <?php if($i==1) echo '<div class="row">' ;?>
    
            <div class="col-sm-6">
                <?php the_title();?>
            </div>
    
            <?php if($i==2) echo '</div>' ; ?>
    
        <?php $i++; if($i>2)$i=1;endwhile; wp_reset_query();if($i==2) echo '</div>' ;?>
    
  2. Give this a try

    <?php $i = 2; ?>
    
    <?php while (have_posts()) : the_post(); ?>
        <?php if ($i == 2 || $i % 2 == 0) echo '<div class="row">'; ?>
    
        <div class="col-sm-6">
            <?php the_title(); ?>
        </div>
    
        <?php if ($i == 2 || $i % 2 == 0) echo '</div>'; ?>
    
        <?php $i++;
    endwhile;
    wp_reset_query(); ?>
    
  3. Keep the count of number of div’s that are open

    Change this

    <?php if($i==1 || $i%2==1) echo '<div class="row">';?>
    

    to

    <?php if($i==1 || $i%2==1){ echo '<div class="row">'; $count = 1;} ?>
    

    And Check if count==1 while closing the div

    <?php if($count==1){ echo '</div>' ; $count=0; } ?>