将活动类添加到wordpress循环的第一项

Rob*_*son 1 php wordpress wordpress-theming

我在WordPress的类别上创建了滑块并发布了缩略图。

我试图将活动类添加到循环中的第一个项目,但循环在所有项目中显示该类。

我该如何解决?

这是我的循环:

<div class="carousel-inner" role="listbox">

    <?php
        $c = 0;
        $class = '';
        query_posts('category_name=slider&showposts=3');
        if ( have_posts() ) : while ( have_posts() ) : the_post();
            $c++;

            $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'thumbnail' );
            $url = $thumb['0'];

            if ( $c == 1 ) $class .= ' active';
                ?>
                 <div class="item <?php echo $class; ?>">
                     <img src="<?php echo $url; ?>" class="img-responsive" alt="...">
                     <div class="carousel-caption">
                          <h2><?php the_content() ?></h2>
                     </div>
                 </div>
                 <?php
        endwhile;endif;
        wp_reset_query();
    ?>

</div>
Run Code Online (Sandbox Code Playgroud)

http://pastebin.com/R5XA3ik9

Yat*_*dra 5

尝试用这个

 if ( $c == 1 )
    $class = ' active';
 else
    $class=''; 
Run Code Online (Sandbox Code Playgroud)

或者

就在一行中

$class = ($c == 1) ? 'active' : '';
Run Code Online (Sandbox Code Playgroud)


小智 5

另一个答案是正确的,

您可以使用以下代码使代码更好

$class = ($c == 1) ? 'active' : '';
Run Code Online (Sandbox Code Playgroud)