有关PHP

时间:2018-05-23 13:12:19

标签: php wordpress posts

我很尴尬,因为我正在使用滑块来显示最近的帖子。我正在使用Carousel Bootstrap,这是我的代码:

<?php
        $lastposts = get_posts( array(
            'posts_per_page' => 3,
                'category' => 584
        ) );

        if ( $lastposts ) { ?>
            <div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel">
              <div class="carousel-inner">



            <?php foreach ( $lastposts as $post ) :
                setup_postdata( $post ); ?>
                        <div class="carousel-item active">
                        <img src="/wp-content/uploads/slider.png">
                                <div class="carousel-caption d-none d-md-block">
                                    <div class="title">
                                        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                                    </div>
                                </div>
                            </div>

            <?php
            endforeach;
            wp_reset_postdata();
        }
?>
</div>
</div>

问题是我的所有物品都是&#34;活跃的&#34;。

我该如何解决?仅将第一个项目设为有效。

1 个答案:

答案 0 :(得分:2)

尝试使用计数器变量:

<?php
        $lastposts = get_posts( array(
            'posts_per_page' => 3,
                'category' => 584
        ) );

        if ( $lastposts ) { ?>
            <div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel">
              <div class="carousel-inner">


            <?php $counter = 1; ?>
            <?php foreach ( $lastposts as $post ) :
                setup_postdata( $post ); ?>
                        <div class="carousel-item <?php echo ($counter==1) ? "active" : ""; ?>">
                        <img src="/wp-content/uploads/slider.png">
                                <div class="carousel-caption d-none d-md-block">
                                    <div class="title">
                                        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                                    </div>
                                </div>
                            </div>

            <?php
                $counter++;
            endforeach;
            wp_reset_postdata();
        }
?>
</div>
</div>