如何实现WordPress文章按3个、2个交替分组包裹显示?
解决方案
要实现3个项目一组、2个项目一组交替包裹的效果,你需要跟踪当前分组的目标数量,并在达到数量时切换分组规则。以下是修改后的代码:
<div class="row"> <?php // 定义交替的分组大小:先3个,再2个,循环往复 $group_sizes = [3, 2]; $current_group_index = 0; // 初始使用第一个分组大小(3) $items_in_current_group = 0; while ( have_posts() ) : the_post(); $items_in_current_group++; ?> <div class="item"> <!-- 这里放你的文章内容,比如 the_title(), the_content() 等 --> <?php the_title(); ?> </div> <?php // 检查当前组的项目数是否达到目标 if ( $items_in_current_group === $group_sizes[$current_group_index] ) : // 闭合当前row echo '</div><!-- .row -->'; // 切换分组索引:0→1→0→1... $current_group_index = 1 - $current_group_index; // 重置当前组的项目计数 $items_in_current_group = 0; // 打开新的row(如果还有文章要输出的话) if ( have_posts() ) : echo '<div class="row">'; endif; endif; ?> <?php endwhile; ?> </div><!-- .row -->
代码说明
$group_sizes数组定义了交替的分组规则,第一个元素是3,第二个是2,后续会循环使用这两个值。$current_group_index控制当前使用哪个分组大小,通过1 - $current_group_index实现0和1的切换,从而交替3和2的分组。$items_in_current_group记录当前组已经添加的项目数量,达到目标值时就闭合当前row并切换分组。- 额外判断
have_posts()是为了避免在最后一组结束后,输出多余的空row。
这样就能实现你需要的交替分组效果:先3个项目包裹在row里,接着2个,再3个,再2个,以此类推。
内容的提问来源于stack exchange,提问作者Justus
相关产品推荐
相关产品推荐

