Home » Php » php – Add order numbers to children elements, 1,2,3,4,5

php – Add order numbers to children elements, 1,2,3,4,5

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m trying to output order numbers to elements that are generated from gallery captions.

foreach ( $item['gallery'] as $image ) {
  $lines = intval( apply_filters( 'caption_line', 1 ) );
  for ( $line = 1; $line <= $lines; $line++ ) {
    $attachment_post = get_post( $image['id'] );
    $image_caption = $attachment_post->post_excerpt;
    echo '<span class="dot1" onclick="currentSlide' . $item['unit_link'] . '(' . esc_attr( $line ) . ')">' . $image_caption . '</span>';
    }
}

So I need 1,2,3,4…to be generated for $line, but for what I have tried it only output 1 for all elements, changing 1 $lines = intval( apply_filters( ‘caption_line’, 1 ) ); to higher number shows the number, but also duplicate them.

How to&Answers:

Just figured it out, this does exactly what I was looking for!

foreach ( $item['gallery'] as $key => $image ) {
  $attachment_post = get_post( $image['id'] );
  $image_caption = $attachment_post->post_excerpt;
  $keyplus = $key+1;
     echo '<span class="dot1" onclick="currentSlide' . $item['unit_link'] . '(' .  $keyplus . ')">' . $image_caption . '</span>';
}