2014-01-05 54 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

相关问题