如何为多行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_counterset to 0 to track our position within each row. - For every post in the loop:
- If
$row_counteris 0, we add thefirstclass (this is the start of a new row). - If
$row_counterequals$number_of_cols - 1, we add thelastclass (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.
- If
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
相关产品推荐
相关产品推荐

