Reputation: 4987
I want to add some markup in the while loop, so that each three items are wrapped in a <ul>
and each of the ul
should be wrapped in a div
. There can be maximum 6 items, and I want to get following output:
<div class="one">
<ul>
<li>...</li>
<li>...</li>
<li>...</li>
</ul>
</div>
<div class="two">
<ul>
<li>...</li>
<li>...</li>
<li>...</li>
</ul>
</div>
I am trying following code:
<div class="one">
<ul>
<?php
$i = 0 ;
while (have_posts()) : the_post();
$i++; ?>
<li>...</li>
<?php
if ($i === 3){
echo "</ul></div><div class='two'><ul>";
$right_div = true;
}
?>
}
if ($right_div){
</ul></div>
<?php } ?>
?>
It works fine if there are at least 3 items, but if there are less than 3, then breaks the code as it does not close the ul and div.
It is important to use the while loop because its part of a WordPress theme which uses the while loop to get the posts.
Upvotes: 0
Views: 280
Reputation: 796
Taking reference from http://codex.wordpress.org/Function_Reference/have_posts
function more_posts() {
global $wp_query;
return $wp_query->current_post + 1 < $wp_query->post_count;
}
if (!more_posts()){
echo "</ul></div><div class='two'><ul>";
$right_div = true;
}
Oh and i am not a wordpress guy :P
Upvotes: 0
Reputation: 243
Im not sure I get it, but I think the problem is:
if ($right_div){
</ul></div>
<?php } ?>
That should not be a condition, that should be always printed.
Upvotes: 1
Reputation: 664
If I'm understanding correctly, you're saying you want to group things in group of 3's, but if you have 11 items or something like that it breaks. If that's the case, then on the last iteration of the while loop you should close the ul and div elements.
Like so:
if(condition){
echo "</ul></div>";
}
Upvotes: 0