I have a query as shown below:

    $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>

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"


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


Do you mean something like the following?

$query = new WP_Query($wpplnum);

$first = TRUE;


   $class = "";
      $class = "active";
      $first = FALSE;

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



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