user1355300
user1355300

Reputation: 4987

wrapping items in a while loop

I want to add a div tag in a while loop after every 2 items.

I am trying with the following code, but it adds an extra empty <div></div> at the end.

$i = 0;
while ( have_posts() ) : the_post();
    $i++;   
    if ($i == 1){$output .= "<div>";}

    if ($i % 2 == 0){$output .= "</div><div>";}

    endwhile;
if ($i % 2 != 0){$output .= "</div>";}

Upvotes: 0

Views: 431

Answers (2)

hakre
hakre

Reputation: 197757

You need to wrap the logic more. Because if you have 0 elements you don't need any wrapping. If you have even elements, you don't need the extra wrapping at the end.

I add two new functions here, I think it's clear what they do: div_open() and div_close(). The following modification of your pseudo-code then should outline how it works:

if ( have_posts(  ) )
{

    div_open(  );

    for ($counter = 0; have_posts(  ); $counter++)
    {

        the_post(  );

        ...

        if ( $counter && have_posts(  ) && $counter % 2 == 0 )
        {

            div_close(  );

            div_open(  );

        }

    }

     div_close(  );

}

Upvotes: 1

gronostaj
gronostaj

Reputation: 2282

Try adding your additional </div><div> at the beginning of next iteration:

$i = 0;
$div = '';
while ( have_posts() ) : the_post();
    $i++;
    $output .= $div;
    if ($i == 1){$output .= "<div>";}

    if ($i % 2 == 0){$div = "</div><div>";}
    else {$div = '';)

    endwhile;
if ($i % 2 != 0){$output .= "</div>";}

Upvotes: 1

Related Questions