Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();?>
like image 600
RMH Avatar asked Feb 02 '26 19:02

RMH


2 Answers

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>' ;?>
like image 83
Raúl Millán Avatar answered Feb 05 '26 08:02

Raúl Millán


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(); ?>
like image 45
Umair Ayub Avatar answered Feb 05 '26 08:02

Umair Ayub