Empty div being created in this wp loop

Hi,

I have some code that looks like this:

				<div class="sponsor-slide__inner">

					<?php while($the_query->have_posts()) : $the_query->the_post(); ?>

						<div class="sponsor">
							<img src="<?php the_field('logotyp'); ?>" alt="<?php the_title(); ?>" />
						</div>

					<?php $counter++;
		              if ($counter % 4 == 0) {
		              	echo '</div></div><div class="sponsor-slide"><div class="sponsor-slide__inner">';
		            }
		            endwhile; ?>

		        </div>

As you can see I wrap the posts in “rows” of four. However if I have 8 posts (two rows) an empty third row is created also. What is wrong with my code?

It looks as though your

echo '</div></div><div class="sponsor-slide"><div class="sponsor-slide__inner">';

is closing two divs that aren’t open, unless I’m missing something.

Sorry i forgot some markup:S

this is how it looks:

<div class="sponsor-slide">
	<div class="sponsor-slide__inner">

	<?php while($the_query->have_posts()) : $the_query->the_post(); ?>

		<div class="sponsor">
			<img src="<?php the_field('logotyp'); ?>" alt="<?php the_title(); ?>" />
		</div>

	<?php $counter++;
      if ($counter % 4 == 0) {
      	echo '</div></div><div class="sponsor-slide"><div class="sponsor-slide__inner">';
    }
    endwhile; ?>

    </div>
</div>

What value did you initialize your $counter at?

It gets incremented after the post query. If you started at 0, then $counter = 4 will be the beginning of a new row.

At 0.

How should the code look like If I don’t want an empty row after every four posts? Atm I have 12 posts so my markup llooks like:

<div class="sponsor-slide">
    <div class="sponsor-slide__inner">
    <!-- 4 posts -->
    </div>
</div>
<div class="sponsor-slide">
    <div class="sponsor-slide__inner">
    <!-- 4 posts -->
    </div>
</div>
<div class="sponsor-slide">
    <div class="sponsor-slide__inner">
    <!-- 4 posts -->
    </div>
</div>
<div class="sponsor-slide">
    <div class="sponsor-slide__inner">
    <!-- empty row -->
    </div>
</div>

Doesn’t this line always add an empty div? You just happened to place it after the fourth div.

Why don’t you use CSS with your rows to make sure only four divs will fit in one ‘row’ instead.

Naa it wraps 4 posts and then starts a new “row”. But I only want it to do this if there is a fifth post.

I can’t do it with CSS since every “row” is a slide in a slider.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.