Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress post loop with incremental value

I have a loop that displays a list item (for a slider) for each post looped like so:

<?php while (have_posts()) : the_post(); ?>
<li data-target="#myCarousel" data-slide-to="0"<?php if( $wp_query->current_post == 0 && !is_paged() ) { ?> class="active"<?php } else { ?><?php } ?>></li>
<?php endwhile; ?>

However I need to increase the value of data-slide-to by 1 for each list item it produces. If for instance the loop had 3 posts the end result looking like this:

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

How can I incrementally increase the data-slide-to value?

like image 444
jessback Avatar asked Jun 16 '26 19:06

jessback


1 Answers

Add a counter to while loop:

<?php 
  //We want to start with 0 so $counter will be -1
  $counter = -1;
  while (have_posts()) : the_post(); $counter++ 
?>

<li data-target="#myCarousel" data-slide-to="<?php echo $counter; ?>"<?php if( $wp_query->current_post == 0 && !is_paged() ) { ?> class="active"<?php } else { ?><?php } ?>></li>

<?php endwhile; ?>
like image 111
iEmanuele Avatar answered Jun 19 '26 08:06

iEmanuele