2014-01-05 104 views
2

我正在使用隨引導程序提供的傳​​送帶。這我將在WordPress中使用。我用foreach循環查詢兩個最近發佈的帖子,但爲了使輪播正常工作,我需要最新的帖子來有一個額外的「主動」類。我在這裏找到了一些解決方案,但它都是while循環,我真的需要這個foreach循環。這是我的代碼:向(foreach)循環中的第一個div添加一個類

<div id="NewsCarousel" class="carousel slide"> 
      <div class="carousel-inner"> 
      <?php 
      $args = array('numberposts' => '2', 'category' => 5); 
      $recent_posts = wp_get_recent_posts($args); 
      foreach($recent_posts as $recent){ 
       echo '<div class="item"><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . get_the_post_thumbnail($recent["ID"], array(200,200)) .$recent["post_title"].'</a> </div> '; 
      } 
      ?> 
      </div> 
     </div> 
+0

循環類型應該沒有關係,添加一個計數器,第一次迭代添加類 – 2014-01-05 22:31:33

+0

...或者使用'$ recent_posts'數組鍵,如果它們保證爲零基於 – zerkms

回答

2

您可以在foreach循環之外添加一個像$count = 0;這樣的計數器。然後foreach循環裏面你告訴它增加像這樣$count++;

然後檢查計數等於1是這樣的:if($count == 1){//do this}

所以你的情況可以做這樣的:

<div id="NewsCarousel" class="carousel slide"> 
<div class="carousel-inner"> 
<?php 
$args = array('numberposts' => '2', 'category' => 5); 
$recent_posts = wp_get_recent_posts($args); 
$count = 0; 
foreach($recent_posts as $recent){ 
$count++; 
    echo '<div class="item'; if($count == 1){echo ' active';}"><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . get_the_post_thumbnail($recent["ID"], array(200,200)) .$recent["post_title"].'</a> </div> '; 
} 
?> 
</div> 
</div> 

嘗試一下,它應該做的伎倆。我剛剛在我正在處理的項目中使用這種方法。

3

可以使用boolean變量來確定它是否是第一循環或沒有。初始值爲true,一旦循環,值就設置爲false

<div id="NewsCarousel" class="carousel slide"> 
    <div class="carousel-inner"> 
    <?php 
    $args = array('numberposts' => '2', 'category' => 5); 
    $recent_posts = wp_get_recent_posts($args); 
    $isFirst = true; 
    foreach($recent_posts as $recent){ 
     echo '<div class="item' . $isFirst ? ' active' : '' . '"><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . get_the_post_thumbnail($recent["ID"], array(200,200)) .$recent["post_title"].'</a> </div> '; 
     $isFirst = false; 
    } 
    ?> 
    </div> 
</div> 
+1

比我的更好的主意,大腦仍然在假期 – 2014-01-05 22:40:39

+0

+1尼斯欺騙... –

+0

不起作用,我得到了x次主動迴應的單詞,沒有課,什麼都沒有。 – Pieter

相關問題