简体   繁体   English

在while循环中分组项目

[英]Group items in while loop

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 . 我想在while循环中添加一些标记,以便将每三个项目包装在<ul>并将每个ul包装在div There can be maximum 6 items, and I want to get following output: 最多可以有6个项目,我想得到以下输出:

<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. 如果至少有3个项目,则工作正常,但如果少于3个,则由于不关闭ul和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. 使用while循环很重要,因为它是WordPress主题的一部分,该主题使用while循环获取帖子。

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. 那不应该是一个条件,应该始终打印出来。

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. 如果我没有正确理解您的意思,那是说您希望将事物分组为3,但是如果您有11个条目或类似的条目,它就会损坏。 If that's the case, then on the last iteration of the while loop you should close the ul and div elements. 如果是这样,那么在while循环的最后一次迭代中,您应该关闭ul和div元素。

Like so: 像这样:

if(condition){
     echo "</ul></div>";
}

Taking reference from http://codex.wordpress.org/Function_Reference/have_posts 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 哦,我不是wordpress的家伙:P

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM