Carla Dessi
Carla Dessi

Reputation: 9666

Adding different class to first div in loop

I have the following code:

<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>

<div class="item">
  <?php the_post_thumbnail('full');?>
  <div class="container">
    <div class="carousel-caption">
      <h1>
        <?php the_title(); ?>
      </h1>
      <p>
        <?php the_excerpt(); ?>
      </p>
    </div>
  </div>
</div>
<?php endwhile; ?>

And I need to add the class "active" to the first div (next to "item")

Upvotes: 2

Views: 3172

Answers (4)

Alex Tangerine
Alex Tangerine

Reputation: 1

<script type="text/javascript">
$('.carousel-inner > :first-child').addClass("active");
</script>

Upvotes: 0

Alex
Alex

Reputation: 68406

if($loop->current_post == 1){
  echo 'class';
}

Upvotes: 0

SamT
SamT

Reputation: 10610

Add a flag:

<?php 
    $isFrist = true;
    while ( $loop->have_posts() ) : $loop->the_post();
?>

<div class="item">
  <?php the_post_thumbnail('full');?>
  <div class="container<?php if ($isFirst): ?> active<?php endif ?>">
    <div class="carousel-caption">
      <h1>
        <?php the_title(); ?>
      </h1>
      <p>
        <?php the_excerpt(); ?>
      </p>
    </div>
  </div>
</div>
<?php
    $isFrist = false;
    endwhile;
?>

Upvotes: 2

Patrick Evans
Patrick Evans

Reputation: 42736

Use a boolean variable to test, set it to true after first pass so that further loops will not mark it active

<?php $firstMarked = false; ?>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
<div class="item <?php echo !$firstMarked ? "active":"";?>">
  <?php the_post_thumbnail('full');?>
  <div class="container">
    <div class="carousel-caption">
      <h1>
        <?php the_title(); ?>
      </h1>
      <p>
        <?php the_excerpt(); ?>
      </p>
    </div>
  </div>
</div>
<?php $firstMarked = true;?>
<?php endwhile; ?>

Upvotes: 4

Related Questions