如何在PHP中实现多样式div结构的WordPress文章动态循环
实现方案
你可以通过添加循环计数器动态控制外层col容器的开关,完全保留原有文章卡片逻辑和设计效果,修改后的代码如下:
<div class="row justify-content-center"> <?php // 初始化文章计数器与容器状态标记 $post_count = 0; $col_opened = false; while($projects_array->have_posts()): $projects_array->the_post(); // 计算当前文章在3篇周期内的位置 $current_in_group = $post_count % 3; // 符合条件时开启新容器:新组第1篇、每周期第3篇 if ($current_in_group === 0 || $current_in_group === 2) { // 先关闭之前开启的容器 if ($col_opened) { echo '</div>'; } // 开启新的col容器 echo '<div class="col-xl-3 col-lg-6 col-md-6">'; $col_opened = true; } // 原有的文章卡片逻辑完全保留 $idd = get_the_ID(); $terms = wp_get_post_terms(get_the_ID(), 'project_cat'); $output = array(); if ($terms) { $i = 1; foreach ($terms as $term) { if($i == 1): $output[] = '<span class="tag-'.$i.'">'.$term->name.'</span>'; $id[] = $term->term_id ; endif; $i++; } } if ( class_exists('ACF') && get_field('choose_link_type') == 1 ) { $post_link = get_the_permalink(); } else { $post_link = get_field('external_link'); } ?> <div class="single-portfolio-box"> <?php if(has_post_thumbnail()): ?> <img src="<?php the_post_thumbnail_url(); ?>" alt="<?php the_post_thumbnail_caption(); ?>"> <?php endif; ?> <div class="content"> <h3><a href="<?php echo esc_url( $post_link ); ?>"><?php the_title(); ?></a></h3> <?php echo join( ' ', $output ); ?> </div> </div> <?php $post_count++; endwhile; // 关闭最后一个未闭合的容器 if ($col_opened) { echo '</div>'; } wp_reset_query(); ?> </div>
逻辑说明
- 以3篇文章为一个周期,自动将每周期前2篇放入同一个
col容器,第3篇单独放入新的col容器,完全匹配你需要的DOM结构 - 原有文章的分类输出、链接判断、缩略图渲染等逻辑完全未改动,不会影响现有设计效果
- 自动处理最后不足3篇的边界场景,不会出现未闭合的HTML标签
内容的提问来源于stack exchange,提问作者jesica
相关产品推荐
相关产品推荐

