WordPress Index.php中每四个cfcolumn用带类Div容器包裹的需求
Group Every 4
.cfcolumn Elements in WordPress Loop Got it, let's tweak your loop so every four .cfcolumn items get wrapped in a custom container div. I'll adjust your existing code step by step, with clear breakdowns of the key changes:
Modified Full Working Code
<div id="left-area" style="padding-top: 58px;"> <!-- #custom-area --> <?php // Initialize a counter to track how many posts we've processed $column_counter = 0; while ( have_posts() ) : the_post(); // Open a new custom container at the start of every 4-item group if ( $column_counter % 4 === 0 ) : ?> <div class="cf-column-group"> <!-- Replace this class with your custom one --> <?php endif; ?> <div class="cfcolumn"> <a href="<?php echo get_field('upload_pdf_book'); ?>"> <img src="<?php echo get_field('cover_picture'); ?>" alt="<?php the_title(); ?>" > </a> </div> <?php $column_counter++; // Close the container after every 4th item if ( $column_counter % 4 === 0 ) : ?> </div> <?php endif; ?> <?php endwhile; // end of the loop. ?> // Cleanup: Close the last container if there are leftover items (less than 4) <?php if ( $column_counter % 4 !== 0 ) : ?> </div> <?php endif; ?> <!-- #custom-area --> </div> <!-- #left-area -->
Key Changes Explained:
- We added a
$column_countervariable to keep track of how many posts we've looped through. - The
$column_counter % 4 === 0check triggers opening a new container at the start of each 4-item set (works for the first item, 5th item, 9th, etc.). - After incrementing the counter, we check again to close the container once we hit the 4th item in a group.
- The final post-loop check ensures we don't leave an unclosed container if your total post count isn't a perfect multiple of 4 (like 5, 7, or 9 posts).
Quick note: Feel free to rename cf-column-group to whatever custom class name you need for your styling—just make sure it matches your CSS rules!
内容的提问来源于stack exchange,提问作者Usama Shah
相关产品推荐
相关产品推荐

