2011-05-03 91 views
0

我想了解如何在while循環輸出的第一個和最後一個項目上添加第一個和最後一個類。我通過搜索找到的唯一東西與直接使用mysql有關,而我在Wordpress循環中使用它(我已經放入了一個函數,我想創建類osu_first_last()):PHP在while循環中的第一個和最後一個類

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

任何人都可以建議最好的方式來做到這一點嗎?

感謝,

OSU

+0

爲什麼不使用CSS? '#news-loop div:first-child {}'和'#news-loop div:last-child {}' – Gordon 2011-05-03 10:56:47

+0

嗨Gordon - 不幸的是,它看起來像IE不支持這些選擇器:http:// www。 quirksmode.org/css/contents.html我寧願只用CSS來做! – Osu 2011-05-03 14:00:58

回答

0

您可以同時使用current_postpost_count並通過查詢其傳遞到osu_first_last()來確定第一和最後一篇

然後實現osu_first_last()像這樣

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; 
} 

在你的代碼中它看起來像這樣:

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

謝謝你。這裏是我的基於這個建議的函數:'function osu_first_last($ total_posts,$ posts_count){if} $ {$ posts_count == 0} ($ posts_count + 1)== $ total_posts){ \t \t $ class ='last'; \t} \t return $ class; }' – Osu 2011-05-03 14:24:59

+0

實際上,你的功能看起來更好,所以我會去那個 - 再次感謝! – Osu 2011-05-03 14:26:08

0

隨着count($wp_news_query->posts)你應該得到查詢的帖子/頁面返回的數量。並與$wp_news_query->current_post你得到當前職位/頁面的索引(所以從0開始...)

相關問題