I have the following code:
$loop = 0;
$columns = 3;
<?php while ( have_posts() ) :
the_post();
$loop++;
?>
<li class="<?php if ( $loop % $columns == 0) echo 'last'; if ( ( $loop - 1 ) % $columns == 0 ) echo 'first'; ?>">
</li>
What I want to achieve is:
<li class="first"></li>
<li class="last"></li>
<li class="first"></li>
<li class=""></li>
<li class="last"></li>
<li class="first"></li>
<li class=""></li>
<li class="last"></li>
What I am getting is (which makes sense..):
<li class="first"></li>
<li class="=""></li>
<li class="last"></li>
<li class="first"></li>
<li class=""></li>
<li class="last"></li>
<li class="first"></li>
<li class=""></li>
<li class="last"></li>
meaning the first 2 are given the class first and last respectively and after that it is every 3.
If i was able to use css I would say nth-child(3n+2) but I can't because I want to assign a new class, and I can only assign a style with css.
How can I achieve it with php?
The following will generate the code that you gave as an example:
<?php
$loop = 0;
$offset = 2;
while ($loop < 100) {
echo '<li class="';
if ($loop < $offset) {
if ($loop % 2 == 0) {
echo 'first';
} else {
echo 'last';
}
} else {
if (($loop - $offset) % 3 == 0) {
echo 'first';
} elseif (($loop - $offset + 2 ) % 3 == 0) {
echo '';
} else {
echo 'last';
}
}
echo '"></li>';
++$loop;
}
If the $loop
variable is under the offset it print first
and last
alternately otherwise it will check divisibility with 3, giving the dividend an extra offset for each condition so they will be true
sequentially.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.