Add the “active” class only to the first loop item in a WordPress query [closed]

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

Leave a Comment