Reputation: 355
I would need the following in Wordpress:
<div class="posts-wrapped">
<div id="post-1" class="post">
<h1>Title 1</h1>
</div>
<div id="post-2" class="post">
<h1>Title 2</h1>
</div>
</div>
<div class="posts-wrapped">
<div id="post-3" class="post">
<h1>Title 3</h1>
</div>
<div id="post-4" class="post">
<h1>Title 4</h1>
</div>
</div>
I know how to get posts with WP loop, but how can I wrap every two posts in .posts-wrapped div?
I fetch the posts with WP_Query.
Thanks!
EDIT: So I tried few ways to do it. For example with this:
$index=0;
<div class="posts-wrapped">
<?php
while ( have_posts() ) {
$index++;
?>
<div class="post">
<h1><?php the_post(); ?></h1>
</div> <?php
if(($index % 2) ==0){
echo '</div><div class="posts-wrapped">';
}
} ?>
</div>
But this prints one extra empty posts-wrapped div:
<div class="posts-wrapped">
Lorem ipsum 1<br>
Lorem 2 ipsum est<br>
</div>
<div class="posts-wrapped">
Lorem ipsum 1<br>
Lorem 2 ipsum est<br>
</div>
<div class="posts-wrapped">
</div>
How can i get rid of this last empty div? It screws my carousel (this content is part of carousel).
Upvotes: 0
Views: 782
Reputation: 4870
<?php
$i = 0;
if (have_posts()) :
while (have_posts()) : the_post();
if($i == 0) {
echo '<div class="posts-wrapped">';
} ?>
<div class="post">
<h1><?php the_title(); ?></h1>
</div>
<?php
$i++;
if($i == 2) {
$i = 0;
echo '</div>';
}
endwhile;
if($i > 0) {
echo '</div>';
}
?>
Would you please try above code?
Upvotes: 0
Reputation: 64466
Get the index that counts the loop iteration and check the modulus operation to know that its even or odd
$index=0;
<div class="posts-wrapped">
<?php
while ( have_posts() ) {
$index++;
?>
<div class="post">
<h1><?php the_post(); ?></h1>
</div> <?php
if(($index % 2) ==0){
echo '</div><div class="posts-wrapped">';
}
} ?>
</div>
Upvotes: 1
Reputation: 238
this should work:
<?php
while(have_posts()){
the_post();
?>
<div class="posts-wrapped">
<div class="post">
<h1><?php the_title(); ?></h1>
</div>
<?php
if(have_posts()){ //Makes sure you have another post
the_post();
?>
<div class="post">
<h1><?php the_title(); ?></h1>
</div>
<?php
}
?>
</div>
<?php
}
?>
Upvotes: 0