Shafi Zahid
Shafi Zahid

Reputation: 35

Add class every third <li> throug Php

I get dynamic post in WordPress. But I want to add class after every third <li>.

Like this.

<li></li>
<li></li>
<li class="last_child"></li>
<li></li>
<li></li>
<li class="last_child"></li>

Upvotes: 0

Views: 1286

Answers (2)

Mala
Mala

Reputation: 14803

Assuming you're creating them via for-loop, you can just check on the index. Something like this:

for ($i=0; $i<$num_lis; $i++) {
    echo '<li'.($i % 3 == 2 ? ' class="last_child"' : '').'></li>';
}

Or if you prefer not to use ternary notation:

for ($i=0; $i<$num_list; $i++) {
    if ($i % 3 == 2) {
         echo '<li class="last_child"></li>';
    } else {
         echo '<li></li>';
    }
}

But as j08691 comments, you're probably better off simply selecting every third li in whatever it is that you have using the last_child class, i.e. nth-child for CSS, e.g.

li:nth-child(3n) {
 styles
}

Upvotes: 3

Felix
Felix

Reputation: 38102

You can just use CSS:

li:nth-child(3n) { 
    /* Your styles here */
}

Also as an option, Wordpress has built in jQuery, so you can also use .addClass():

$("ul li:nth-child(3n)").addClass("last_child");

Upvotes: 2

Related Questions