Abhik
Abhik

Reputation: 674

How to add "first" and "last" class to rows of divs?

I am trying to add class first to the first div of a row and class last to the last div of a row. The number of divs in a row is user selectable and stored in a variable. the total number of divs is also user selectable and stored in a variable.

Here's what I have tried, but it adds the class only to the first row and not repeating for the rest.

$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; ?>  

How do I make it repeat for all divs pragmatically?

Thanks

Upvotes: 2

Views: 118

Answers (2)

Tayyab Khan
Tayyab Khan

Reputation: 283

Use this code it will work for you:

<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>

Upvotes: 0

jeroen
jeroen

Reputation: 91734

You can take advantage of the modulos operator, the remainder after a division:

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

When count is 1, 5, etc., the remainder is 1 and when count is 4, 8, etc. the remainder is 0.

Upvotes: 3

Related Questions