每隔一个项目包装 Wordpress 查询的输出

Wrap outputs of a Wordpress query every second item

我想我已经非常接近解决方案了,但我无法弄清楚我应该在哪里关闭最后一个 div。

我有一个 wordpress 查询请求四个 posts。

我想在 <section class="sponsor-row">

中包装每两个项目

所以我在我的查询中实现了一个计数器来计算每个 post,如果它发现两个 post 已经输出,它会关闭 <section> div关闭。

但是我不知道如果该行应该再次关闭我应该如何计算。

谁能解决这个问题?我怎样才能让它在 <section class="sponsor-row"> 中每两个输出包装一次?

if ( $the_query->have_posts() ) {
        while ( $the_query->have_posts() ) {
                $the_query->the_post();

                $counter = 0;
                echo '<section class="sponsor-row">'; // Opening the section here

                        if ( has_post_thumbnail() ) {
                                $counter++;

                                echo '<div class="grid half">';
                                        echo '<a class="sponsor" href="'.get_the_permalink().'" target="_blank">';
                                        the_post_thumbnail( 'full' );
                                        echo '</a>';  
                                echo '</div>';

                                if ($counter <= 2){
                                        echo '</section>'; // closing the section if two posts
                                        $counter = 0;
                                }
                        }
                }
        }

此处完整查询:http://pastebin.com/e6RzZLR5

如果你这样做 if ($counter <= 2){ 那么它会在每次小于或等于 2 时关闭它,这意味着它会为每个项目关闭两次。您应该使用 if ($counter == 2){ 并且 $counter = 0; 应该在查询之前位于顶部,否则您将在每个循环中将其设置为 0。

See comparison in php