WordPress循环计数器问题:自定义文章类型列表换行异常修复
Let's break down what's happening here, explain why your initial PHP counter logic didn't behave as expected, and confirm the solid CSS fix you implemented.
Your Original Setup
You're looping through the short_courses custom post type (filtered to digital-marketing course_type) with this WordPress code:
<div class="wrap" style="padding-top: 0 !important;"> <?php $args = array( 'post_type' => 'short_courses', 'course_type' => 'digital-marketing' ); $the_query = new WP_Query( $args ); ?> <?php if ( have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?> <div class="one-third course-item"> <a href="<?php the_permalink(); ?>"> <p><img src="<?php the_field('listing_thumbnail'); ?>"></p> <h4><?php the_title(); ?></h4> <p style="color: #f08464;"><?php the_field('date_for_thumbnail_listing'); ?></p> <p><?php the_field('price'); ?></p> <a href="<?php the_permalink(); ?>" class="sc-box-button" style="background-color: #f08464; margin-bottom: 40px;">MORE INFO</a> </a> </div> <?php $products_count = $the_query->current_post + 1; ?> <?php if ( $products_count % 4 == 0): ?> <?php endif; ?> <?php endwhile; wp_reset_postdata(); endif; ?> </div>
Why the PHP Counter Didn't Work
Your conditional check if ( $products_count % 4 == 0): has no content inside the block—you aren't outputting any HTML to force a line break or wrap items into a new row. This means the counter logic was completely inactive, and the actual 3-items-per-row layout was controlled by your existing CSS (likely a default column-count: 3 rule on a parent container).
The CSS Fix You Implemented
You resolved the issue perfectly by updating your CSS to enforce a 4-column layout for larger screens:
@media (min-width: 576px) { .card-columns { column-count: 4; } }
This directly overrides the default 3-column behavior, ensuring exactly 4 course items appear per row on screens wider than 576px—clean and effective for responsive layouts.
Bonus: Fixing the PHP Counter Logic (If You Prefer a PHP-Driven Layout)
If you ever want to use PHP to handle row wrapping instead of CSS columns, you'd need to add HTML output inside the conditional to split rows. For example:
<?php $products_count = $the_query->current_post + 1; ?> <?php if ( $products_count % 4 == 0): ?> </div><div class="row"> <!-- Close the current row container, open a new one --> <?php endif; ?>
Just make sure you start with an opening <div class="row"> before the loop, and close it after the loop ends to keep your HTML valid.
内容的提问来源于stack exchange,提问作者Shaun Taylor

