Reputation: 681
I want to add a class "first" on the first column of five columns in a wordpress loop. Please see sample below
<div class="box first"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box first"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
I tried doing something like this but it doesnt seem to work
global $wp_query;
$wp_query = new WP_Query( $args );
if ( have_posts() ) :
echo '<div class="row">';
while ( have_posts() ) : the_post();
for ($i=0; $i<$num_list; $i++) {
if ($i % 5 == 1) {
echo '<div class="box first"></div>';
} else {
echo '<div class="box"></div>';
}
}
endwhile;
echo '</div>';
endif;
wp_reset_query();
Upvotes: 0
Views: 801
Reputation: 10824
You can achieve the same result without adding a special class, but setting a rule that matches every 5th element. Here's an example:
.box{
border: 1px solid black;
width: 20px;
height: 20px;
margin: 3px;
}
.box:nth-child(5n+1){
border: 1px solid red;
background-color: #e5e5e5;
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
Upvotes: 1
Reputation: 19764
Using modulo is a good choice. But should be compared to zero instead of one :
for ($i=0; $i<$num_list; $i++) {
if ($i % 5 == 0) {
echo '<div class="box first"></div>';
} else {
echo '<div class="box"></div>';
}
}
Upvotes: 1