开发者

PHP first and last classes in a while loop

I'm trying to work out how to add a first and last class on the first and last items outputted from a while loop. The only thing I've found through searching has been relevant to working with mysql directly, while I'm using this in a Wordpress loop (I've put in a function where I want to create the class osu_first_last()):

<div id="news-loop">
    <h2 class="widget-title">News</h2>
    <?php
        // Build query for 
        $wp_news_query_temp = clone $wp_query;
        $wp_news_query = new WP_Query();
        $wp_news_query->query('category_name=News&showposts=3&orderby=date&order=DESC');
   开发者_如何学编程     $news_counter = 0;
        // Create posts loop
        if ($wp_news_query->have_posts()) : while ($wp_news_query->have_posts()) : $wp_news_query->the_post(); ?>
        <div class="news-entry news-entry-<?php echo $news_counter; ?><?php osu_first_last(); ?>">
            <h3 class="entry-title">
            <?php the_title(); ?>
            </h3>
            <?php twentyten_posted_dateonly(); ?>
            <?php echo osu_short_excerpt(); ?>
        </div> <!-- End div.news-entry -->
        <?php
        $news_counter++;
        endwhile; ?>
        <?php endif; $wp_query = clone $wp_news_query_temp; ?>
        <a href="<?php bloginfo('url'); ?>/category/news/" class="sidebar-more">View all news</a>   
</div>

Can anyone advise on the best way to do this please?

Thanks,

osu


ou can use the current_post and post_count and to determine the first and last post by passing it along with the query to osu_first_last()

then implement osu_first_last() like this

function osu_first_last($query)
{
    $extraClass = "";
    if($query->current_post == 1)
    {
        $extraClass .= "first";
    }
    if($query->post_count == $query->current_post)
    {
        if($extraClass != "")
        {
            // post is first and last
            $extraClass .= " ";
        }
        $extraClass .= "last";
    }
    return $extraClass;
}

In your code it would look like this:

<div class="news-entry news-entry-<?php echo $news_counter; ?><?php echo osu_first_last($wp_news_query); ?>">


With count($wp_news_query->posts) you should get the number of post/page return by the query. And with $wp_news_query->current_post you get the index of the current post/page (so starting with 0 ... )

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜