Iterating through images for a basic lightbox / sorting

Continuing the discussion from When iterating through my projects, display for each a different icon depending on their order:

I created a simple css only lightbox to iterate over the existing images on the page. Each open lightbox lists previous and next images if they exist. It works really well.

I’d like the images sorted in the panel using ->sort('sort'). But when I add that to the first line, the images on the page are ordered correctly, but once an image is clicked and the lightboxes open up, they’re not sorted the same. I’m guessing it’s my really poor and inefficient PHP.

<?php $images = $page->images() ?>
	<div class="lightbox">

		<?php //create all of the image openers 
		foreach ($images as $image): ?>
			<?php $num = $images->indexOf($image) + 1 ?>
			<a href="#img<?= $num ?>"><img src="<?= $image->resize(100)->url() ?>" /></a>
		<?php endforeach ?>

		<?php //create all of the lightboxes
		foreach ($images as $image):  ?>
			<?php $num = $images->indexOf($image) + 1 // start at 1 ?>
			<div id="img<?= $num ?>" class="lightbox-open">
				<a href="#" class="x"><span>&times;</span></a>

				<?php if ($image->isFirst()) : ?>
					<a href="#" class="lb-link prev">&times;</a>
					<?php else : ?>
					<?php $prev = $num -1 ?>
					<a href="#img<?= $prev ?>" class="lb-link prev">&laquo;</a>
				<?php endif ?>

				<img src="<?= $image->url() ?>"/>

				<?php if ($image->isLast()) : ?>
					<a href="#" class="lb-link next">&times;</a>
					<?php else : ?>
					<?php $next = $num + 1 ?>
					<a href="#img<?= $next ?>" class="lb-link next">&raquo;</a>
				<?php endif ?>
			</div>
		<?php endforeach ?>
	</div>

Also, sometimes the Next link increases by 2! :man_facepalming:
Any thoughts are appreciated.

1 Like