I’m trying to use a Bootstrap carousel in WordPress, so I need to have a loop. However, the slider script requires the first slide to have a special class, and can’t figure how to apply that class to the first iteration of the loop and only to it (in fact the class will rotate throughout the slides when the carousel is working, but the html needs to have first slide with active
class and then all other slides without that class).
here is my code so far:
<div id="myCarousel" class="carousel slide">
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0" class="active"></li>
<li data-target="#myCarousel" data-slide-to="1"></li>
<li data-target="#myCarousel" data-slide-to="2"></li>
</ol>
<!-- Wrapper for Slides -->
<div class="carousel-inner">
<?php if( have_rows('slide') ): ?>
<?php while( have_rows('slide') ): the_row();
// vars
$img = get_sub_field('slide_image');
$desc = get_sub_field('slide_text');
$title = get_sub_field('slide_title');
$url = $img['url'];
$size = 'slider';
$thumb = $gal['sizes'][ $size ];
?>
<div class="item active">
<!-- Set the first background image using inline CSS below. -->
<div class="fill" style="background:url('<?php echo $img; ?>') no-repeat; background-size:cover;"></div>
<div class="carousel-caption">
<h2><?php echo $title; ?></h2>
<div class="desc"><?php echo $desc; ?></div>
</div>
</div>
<?php endwhile;?>
<?php endif;?>
</div>
<!-- Controls -->
<a class="left carousel-control" href="#myCarousel" data-slide="prev">
<span class="icon-prev"></span>
</a>
<a class="right carousel-control" href="#myCarousel" data-slide="next">
<span class="icon-next"></span>
</a>
</div>
and for reference, the original pure HTML code is located at https://github.com/IronSummitMedia/startbootstrap/blob/gh-pages/templates/half-slider/index.html
so, in short, what I need is to have this line:
<div class="item active">
only once, but all the other iterations should be
<div class="item">
It would be something like How to put an class on specific (first element) inside loop?, only that in PHP and WordPress, I tried to follow that answer but couldn’t understand it
Any help really appreciated
If you want just one occurrance, just use an
$i
variable.You can use
$wp_query->current_post
to get the index position in The Loop and then only print out “active” when the$wp_query->current_post == 0
Edit: realized you said “a loop” and not “the loop”, you can just use an variable and if statement to check if it is the first iteration of your loop or not.
I have used:
Works like a breeze!