Using PHP to generate out a list.
I Simply want to set a different class on every fifth entry. (1/5), (4+1)
<li class="<?php the_code();?>"> content </li>
Output would be like this
<li class="yolo"> Content </li>
<li class="yolo"> Content </li>
<li class="yolo"> Content </li>
<li class="yolo"> Content </li>
<li class="hello"> Content </li>
<li class="yolo"> Content </li>
<li class="yolo"> Content </li>
<li class="yolo"> Content </li>
<li class="yolo"> Content </li>
<li class="hello"> Content </li>
How can i do this ?
Guess it's pure basic for anyone with php skills, that's not me but i would also be glad to get pointed towards some page that explains this so i can learn it.
To clarify am using Wordpress loop and it contains +100 items and i want to alter class on item 5,10,15,20,25,30,35 etc..
You can use a counter ($i
) and increment it on each time you create a new list item (++$i
), then check to see if the result is divisible by 5 (% 5 == 0
). Then simply use the ternary operator (?…:…
) to decide which value to output:
<?php $i = 0; ?>
<?php for(...) { ?>
<li class="<?= (++$i) % 5 == 0 ? 'yolo' : 'hello' ?>"> content </li>
<?php } ?>
But it truth, there's no need to even use PHP, when a little CSS will probably do the job:
li:nth-child(5n)
{
...
}
See a demonstation here.
As a drop in function for the code you provided:
function the_code() {
static $count = 0;
$count++;
echo $count % 5 == 0 ? 'hello':'yolo';
}
the static keyword in the function keeps the value of count whenever the function is called.