You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为多行Div添加first和last类?WordPress代码排障

Fix: Add First/Last Classes to Each Row's Divs in WP Loop

The issue with your current code is that you're likely only checking for the first post overall or the last post of the first row, without resetting the counter for subsequent rows. Here's how to adjust your loop to apply the first and last classes correctly to every row's first and last div:

$number_of_cols = 4; // User Selectable
$posts_per_page = 16; // User Selectable
$mas_query = new WP_Query( $args );

// Initialize row counter to track position within the current row
$row_counter = 0;

if ( $mas_query->have_posts() ) :
    while ( $mas_query->have_posts() ) : $mas_query->the_post();
        
        // Start with a base class for your post items
        $post_classes = 'post-item';
        
        // Add 'first' class if this is the first item in the current row
        if ( $row_counter === 0 ) {
            $post_classes .= ' first';
        }
        
        // Add 'last' class if this is the last item in the current row
        if ( $row_counter === $number_of_cols - 1 ) {
            $post_classes .= ' last';
        }
        
        // Output your div with the dynamic classes
        ?>
        <div class="<?php echo esc_attr( $post_classes ); ?>">
            <!-- Your post content goes here -->
            <?php the_title(); ?>
            <?php the_excerpt(); ?>
        </div>
        <?php
        
        // Update the counter and reset it when we reach the end of a row
        $row_counter++;
        if ( $row_counter >= $number_of_cols ) {
            $row_counter = 0;
        }
        
    endwhile;
    wp_reset_postdata(); // Don't forget to reset the post data after custom query
endif;

How This Works:

  • We start with $row_counter set to 0 to track our position within each row.
  • For every post in the loop:
    • If $row_counter is 0, we add the first class (this is the start of a new row).
    • If $row_counter equals $number_of_cols - 1, we add the last class (this is the end of the current row).
    • After outputting the div, we increment the counter. When it hits the number of columns per row, we reset it to 0 to start counting for the next row.

This approach ensures that every row's first and last items get the correct classes, no matter how many columns or total posts you configure.

内容的提问来源于stack exchange,提问作者Abhik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:31:46