2

I have a query as shown below:

<?php
    $query = new WP_Query( $wpplnum );

    while( $query->have_posts() ): $query->the_post();
?>

<div class="carousel-item col-md-4 active">
  <div class="card">
    <img class="card-img-top img-fluid" src="http://placehold.it/800x600/f44242/fff" alt="Card image cap">
    <div class="card-body">
      <h4 class="card-title">Card 1</h4>
      <p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
      <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
    </div>
  </div>
</div>

I want to add the active class only to the first loop item:

class="carousel-item col-md-4 active"

the remaining loop items will be without the active class:

class="carousel-item col-md-4"

closed as off-topic by mmm, Jacob Peattie, bosco, Fayaz, TheDeadMedic Aug 7 '18 at 10:51

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

3

I'd use the current_post property of the WP_Query class instance, which in your case is the $query. So here I check if $query->current_post is greater than or equals to 1:

<div class="carousel-item col-md-4 <?php echo $query->current_post >= 1 ? '' : 'active'; ?>">

Resource: https://codex.wordpress.org/Class_Reference/WP_Query#Properties

1

Do you mean something like the following?

$query = new WP_Query($wpplnum);

$first = TRUE;

while($query->have_posts()):$query->the_post();

   $class = "";
   if($first)
   {
      $class = "active";
      $first = FALSE;
   }
?>

   <div class="carousel-item col-md-4 <?php echo esc_attr( $class ); ?>">

     .....

   </div>

Not the answer you're looking for? Browse other questions tagged or ask your own question.