在(foreach)循环中向第一个div添加一个类

Jer*_*alk 2 php wordpress foreach loops twitter-bootstrap

我正在使用引导程序随附的轮播。我将在WordPress中使用它。我正在用foreach循环查询两个最近的帖子,但是为了使轮播正常工作,我需要最新的帖子才能有一个额外的“活动”类。我在这里在stackoverflow上找到了一些解决方案,但这都是while循环,对于foreach循环,我确实需要它。这是我的代码:

    <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>
Run Code Online (Sandbox Code Playgroud)

Mik*_*ckx 5

您可以使用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>
Run Code Online (Sandbox Code Playgroud)


小智 5

$count = 0;您可以在 foreach 循环之外添加一个类似这样的计数器。然后在 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>
Run Code Online (Sandbox Code Playgroud)

尝试一下,应该可以解决问题。我刚刚在我目前正在处理的一个项目中使用了这种方法。