我认为我已经非常接近这个解决方案了,但我无法找到应该在哪里关闭最后一个div的逻辑。
我有一个wordpress查询,需要四个帖子。
我想用<section class="sponsor-row">
包装每两个项目
因此,我在查询中实现了一个计数器,该计数器对每个帖子进行计数,如果它发现已经输出了两个帖子,则关闭<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。
参见php 中的比较