WP-Mix

A fresh mix of code snippets and tutorials

WordPress Image Gallery Loop

This post shares the custom-loop code referenced by the image gallery tutorial. Basically what we’re doing here is creating a custom loop for displaying images that are attached to the current post (i.e., in the WP Loop). This technique is used for the Responsive Image Gallery.

<div id="lightbox">
	<?php // display image gallery
	$args = array('order'=>'ASC', 'post_type'=>'attachment', 'post_parent'=>$post->ID, 'post_mime_type'=>'image', 'post_status'=>null, 'numberposts'=>9); 
	$items = get_posts($args);
	if ($items) {
		foreach ($items as $item) {
			$atts = wp_get_attachment_image_src($item->ID, 'full');
			$title = get_the_title($item->ID);
			$title_truncated = substr($title, 0, 18);
			if (strlen($title) > 18) {
				$title_display = $title_truncated . '..';
			} else {
				$title_display = $title_truncated . '';	
			} ?>

			<div class="image-thumb">
				<a class="fancybox" rel="gallery" href="<?php echo wp_get_attachment_url($item->ID); ?>" title="Image #<?php echo get_the_title($item->ID); ?>">
					<img src="<?php echo $atts[0]; ?>" width="<?php echo $atts[1]; ?>" height="<?php echo $atts[2]; ?>">
				</a>
				<div class="image-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?>: Image #<?php echo $title_display; ?></a></div>
			</div>
			
		<?php }
	} ?>
</div>

There are a zillion ways to customize this code snippet, for example you can change the number of images that are displayed by changing the value of numberposts from 9 to whatever number makes sense.

Learn more

WordPress Themes In Depth