Php 如何加上「;“第一”;及;最后一句话;类到多行div?

Php 如何加上「;“第一”;及;最后一句话;类到多行div?,php,Php,我试图将classfirst添加到行的第一个div,并将classlast添加到行的最后一个div。行中的div数由用户选择并存储在变量中。div的总数也是用户可选择的,并存储在变量中 这是我尝试过的,但它只将类添加到第一行,而不会重复其他行。 $number_of_cols = 4; //User Selectable $posts_per_page = 16; //User Selectable $mas_query = new WP_Query( $args ); if ( $mas

我试图将class
first
添加到行的第一个div,并将class
last
添加到行的最后一个div。行中的div数由用户选择并存储在变量中。div的总数也是用户可选择的,并存储在变量中

这是我尝试过的,但它只将类添加到第一行,而不会重复其他行。
$number_of_cols = 4;  //User Selectable
$posts_per_page = 16; //User Selectable

$mas_query = new WP_Query( $args );

if ( $mas_query->have_posts() ) :
    $count = 0;
    while ( $mas_query->have_posts() ) : $mas_query->the_post();
        $count++; ?>
        <div class="blog-masonry-grid-items masonry-col-<?php echo $number_of_cols; echo ( $count == 1 || $count == $number_of_cols + 1 ? ' masonry-col-first' : ''); echo ( $count == $number_of_cols ? ' masonry-col-last' : '');?>">
            <div class="grid-item-image-wrap"><?php if ( has_post_thumbnail() ) { the_post_thumbnail('medium_large'); } ?></div>
            <div class="grid-item-content-wrap"><?php the_title( '<h3 class="entry-title grid-entry-title">', '</h3>' );?></div>
        </div>
<?php endwhile; endif; ?>  
$numberofcols=4//用户可选择
每页$posts\u=16//用户可选择
$mas\u query=新的WP\u查询($args);
如果($mas\u query->have\u posts()):
$count=0;
而($mas_query->have_posts()):$mas_query->the_post();
$count++;?>
我怎样才能让它在所有的div中重复


多谢

您可以利用模运算符,除法后的余数:

while ( $mas_query->have_posts() ) : $mas_query->the_post();
    $count++;
    // Boolean values
    $firstOfRow = ($count % $number_of_cols === 1);
    $lastOfRow = ($count % $number_of_cols === 0);

当计数为
1
5
等时,余数为
1
,当计数为
4
8
等时。余数为
0
,使用此代码它将为您服务:

<div class="blog-masonry-grid-items masonry-col-<?php if($count == 1){ echo $number_of_cols.' masonry-col-first'; }else if{($count ==$number_of_cols) echo $number_of_cols.' masonry-col-last';}?>">
<div class="grid-item-image-wrap"><?php if ( has_post_thumbnail() ) { the_post_thumbnail('medium_large'); } ?></div>
<div class="grid-item-content-wrap"><?php the_title( '<h3 class="entry-title grid-entry-title">', '</h3>' );?></div>
</div>