本文介绍了在循环中包装每 3 个元素会留下一个空的包装器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我将循环中的每 3 个元素包装在一个包装 div 中,如下所示:
$query = array('post_type' =>'邮政',);$i = 1;$posts = new WP_Query( $query );$out = '';如果 ($posts->have_posts()){而 ($posts->have_posts()){$posts->the_post();$out.='//内容在这里';if($i % 3 == 0) {$out .= '</div><div class="wrapper">';}$i++;}}$out .='
';wp_reset_postdata();返回 '';
它创建了一个很好的包装 html 减去一件困扰我的小事:
';
I am wrapping every 3 elements in my loop in a wrapper div like this:
$query = array(
'post_type' => 'post',
);
$i = 1;
$posts = new WP_Query( $query );
$out = '<div class="wrapper">';
if ($posts->have_posts()){
while ($posts->have_posts()){
$posts->the_post();
$out.= '<div class="content">
//content here
</div>';
if($i % 3 == 0) {
$out .= '</div><div class="wrapper">';
}
$i++;
}
}
$out .= '</div>';
wp_reset_postdata();
return '<section>'.$out.'</section>';
Which creates a good wrapping html minus one little thing that's bothering me:
<section>
<div class="wrapper">
<div class="content"></div>
</div>
<div class="wrapper">
<div class="content"></div>
</div>
<div class="wrapper"></div>
</section>
If I have exactly 6 posts (or any multiple of 3, and modulo is doing this like it should) I'll get an extra empty wrapper. Which is really not needed.
So what conditional should I include in my query to ensure that I don't get empty wrappers?
解决方案
Add the wrapper inside:
$query = array(
'post_type' => 'post',
);
$i = 1;
$posts = new WP_Query( $query );
$out = '';
$endingNeeded = false;
if ($posts->have_posts()){
while ($posts->have_posts()){
if($i % 3 == 1) {
$out .= '<div class="wrapper">';
$endingNeeded = true;
}
$posts->the_post();
$out.= '<div class="content">
//content here
</div>';
if($i % 3 == 0) {
$out .= '</div>';
$endingNeeded = false;
}
$i++;
}
}
if($endingNeeded) {
$out .= '</div>';
}
wp_reset_postdata();
return '<section>'.$out.'</section>';
这篇关于在循环中包装每 3 个元素会留下一个空的包装器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!