WordPress模板循环中card-deck类重复渲染问题求助
解决WordPress模板中card-deck重复渲染的问题
你的问题核心是card-deck容器被放在了循环内部,导致每生成一篇文章就重复一次这个容器。正确的做法是把card-deck的外层容器移到循环外面,只让循环渲染内部的单个卡片,这样整个卡片组只会生成一次。
修改后的完整代码如下:
<?php // the query $the_query = new WP_Query(array( 'category_name' => 'events', 'post_status' => 'publish', )); ?> <?php if ($the_query->have_posts()) : ?> <div class="card-deck text-center"> <?php while ($the_query->have_posts()) : $the_query->the_post(); ?> <div class="card"> <img src="<?= wp_get_attachment_url(get_post_thumbnail_id()); ?>" class="card-img-top wp-post-image" alt="<?php the_title_attribute(); ?>" style="width:100%; height:auto;" /> <div class="card-body"> <h5 class="card-title"><?php the_title(); ?></h5> <p class="card-text"><?php echo get_post_meta($post->ID, 'Event Date', true); ?></p> <p class="card-text"> <small class="text-muted"> <a href="<?php the_permalink(); ?>">Show More</a> </small> </p> </div> </div> <?php endwhile; ?> </div> <?php else : ?> <p>暂无相关活动文章</p> <?php endif; ?> <?php wp_reset_postdata(); ?> <!-- 重置查询,避免影响后续全局变量 -->
关键修改点:
- 将
<div class="card-deck text-center">移到while循环之前,闭合标签移到循环之后,确保整个卡片组只生成一次 - 添加了
if ($the_query->have_posts())判断,没有文章时显示提示内容,提升用户体验 - 加上
wp_reset_postdata(),重置WP查询的全局变量,避免后续模板代码出现异常
内容的提问来源于stack exchange,提问作者Shundo
相关产品推荐
相关产品推荐

