开发者

Adding a first and last class to Wordpress' widget contents

开发者 https://www.devze.com 2023-02-04 02:46 出处:网络
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:

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".

Is there an easy workaround for this? (I 开发者_C百科don't want to do this with javascript)

Thank you.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消