Adding a first and last class to WordPress’ widget contents

In WordPress, I’m looking for some way to add a “last” and a “first” class to list items inside WordPress widgets. The HTML could look like this:

<div class="widget-area">
<ul >
    <li class="widget_recent_comments">
        <h3 class="widget-title">Recent comments</h3>
        <ul id="recentcomments">
            <li class="recentcomments">Comment 1</li>
            <li class="recentcomments">Comment 2</li>
            <li class="recentcomments">Comment 3</li>
            <li class="recentcomments">Comment 4</li>
        </ul>
    </li>
    <li class="widget_my_links">
        <h3 class="widget-title">My links</h3>
        <ul id="my-links">
            <li class="item">Link 1</li>
            <li class="item">Link 2</li>
            <li class="item">Link 3</li>
            <li class="item">Link 4</li>
            <li class="item">Link 5</li>
        </ul>
    </li>
</ul></div>

In this example above i’d like to have first/last classes added to the li with “Comment 1”, “Comment 4”, “Link 1” and “Link 5”.

Read More

Is there an easy workaround for this? (I don’t want to do this with javascript)

Thank you.

Related posts

Leave a Reply

2 comments

  1. I’m guessing these lists are generated in a loop. So what you could do, is create a variable before you go into the loop, and set it’s value to 1 ($i = 1). Than at the end of the loop, add one up ($i++). Now, where you want the first/last class to appear, you can do

    <?php if($i == 1):
      echo ' first';
    elseif( $i == $number_of_items )
      echo 'last';
    endif;      
    ?>
    

    At $i == $number_of_items, you are comparing the max with the current, so you know you have the last if the statement is true.

    Hope this answers your question.

  2. Well the first-item is easy, just use

    ul#my-list li:first-child {
        /* special styles */
    }
    

    It’s not adding a class, but you can still style it. There is not a similar css rule for :last-child unfortunately