Make A Custom WordPress Gallery from Post Attachment Images

Update: A newer version of this function can be found here:

WordPress Image Attachment Gallery Revisited

* You may still benefit from reading this post, however. If for no other reason, you’ll help validate my existence.

I recently had a client who needed a custom WP image gallery that would let him wrap images around the content of his post. His request was: “I need to be able to insert 6+ images into a post. I want one image above the post content and all the others to be below it. Make it as brainless, fast, and automatic as possible.” I like the way he thinks.

But.. but… Dameian, doesn’t WordPress let you do that?

Yes! And no. WP’s built-in Gallery Shortcode can do it, but it doesn’t offer easy control over image placement. Also only about half of the actual gallery features are available through the media manager interface for some reason. That isn’t exactly end-user friendly. I could, of course, teach the client to insert the Shortcode manually but I’m not going there. I’ve learned that when it comes to clients messing with code of *any* kind (no matter how simple) the Golden Rule is typically Murphy’s Law. Clients like to push buttons and select stuff from drop downs menus. They are typically scared of anything that looks like this: [voodoo = "spooky"]. To create galleries of post attachment images in a user friendly would call for something custom. So here we go!

Gallery Shortcode brushed aside, we’re left with inserting images manually into posts where they want them. Yeah… no thanks. Using WordPress’ built-in image tool to place more than a couple of images into a post is tedious at best and a huge time suck at worst. It could take 15 minutes or more to do what a php function can do in milliseconds. Plus a php function can produce custom code to suit the client’s exact needs.

The solution! Well… my solution via other solutions.

After hours of hot Man-on-Google action, mucking about in the WordPress Codex, two failed suicide attempts (just cries for help really), and a bottle of Jack Daniels, I was able to find two incredibly helpful posts. Here are they are for reference and background:

Programmatically Pull Attachments from WordPress Posts by John Ford

Awesome Image-Attachment Recipes for WordPress by Jeff Starr.

My solution borrows heavily from both John and Jeff’s insights while adding a bit of my own Hackamojo™ brand PHP to the mix for a uniquely satisfying flavor. I tried to take the best of the WordPress Media Manager’s features and combine them with a custom function built into the client’s theme. The function will automatically pull the image attachments from the post and place them exactly where the client wants it, exactly how the client wants it. The client uploads images, fills in the meta information for each image, orders the images how he wants them, then saves his changes.

That’s it. Done.

He doesn’t insert anything into the post or mess with code at all. The function will automagically pull the post attachment images and populate the post in the predefined places he wanted.

Before we go any further, let it be known I am no eLiT3 PHP programmer. Thanks to the Thesis Theme by the always entertaining @Pearsonified, I don’t have to be.

If you want to point out improvements that can be made with my code below please feel free to do so. I’d love to make this as efficient and useful as possible so people can get the most benefit from it.

Here are a few reasons this function might be useful to you.

This function makes it ridiculously simple to put images in your posts automatically and in a variety of ways. It has three settings: size, number of images to show, and an offset. “Size” can either be medium or thumbnail. “Images to show” is how many images you want to place in any given spot within your post. “Offset” tells the function what image number it should start with, counting from the first image in the gallery.

Example Scenarios:

  • Display one image above your post content as a teaser.
  • Display your first gallery image as a medium image and the rest as thumbnails.
  • Display two images here, one there, and another in a third place.
  • Display only images 2 through 6 or 1 through 3 somewhere.

You get the idea. It all depends on where you place the call to the function in your theme and what settings you use.

UPDATE 3/21/2012: According to non-canonical sources, this code may not work under WordPress 3.3.1. I can neither confirm nor deny this, since I myself have not used the function as it is presented here in quite a long time. This code is unsupported, and I have no plans to update it unless a client needs it for some reason. So, as should always be the case with random tidbits found on old blog posts on the Internet, consume at your own risk.

The function

Throw this sucker into your WordPress Theme’s functions.php file. Of, if you’re one of the cool kids who use the Thesis Theme, throw it in your custom_functions.php file:

<?php
function nerdy_get_images($size = 'thumbnail', $limit = '0', $offset = '0') {
	global $post;

	$images = get_children( array('post_parent' => $post->ID, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID') );

	if ($images) {

		$num_of_images = count($images);

		if ($offset > 0) : $start = $offset--; else : $start = 0; endif;
		if ($limit > 0) : $stop = $limit+$start; else : $stop = $num_of_images; endif;

		$i = 0;
		foreach ($images as $image) {
			if ($start <= $i and $i < $stop) {
			$img_title = $image->post_title;   // title.
			$img_description = $image->post_content; // description.
			$img_caption = $image->post_excerpt; // caption.
			$img_url = wp_get_attachment_url($image->ID); // url of the full size image.
			$preview_array = image_downsize( $image->ID, $size );
 			$img_preview = $preview_array[0]; // thumbnail or medium image to use for preview.

 			///////////////////////////////////////////////////////////
			// This is where you'd create your custom image/link/whatever tag using the variables above.
			// This is an example of a basic image tag using this method.
			?>

			<img src="<?php echo $img_preview; ?>" alt="<?php echo $img_caption; ?>" title="<?php echo $img_title; ?>">

			<?
			// End custom image tag. Do not edit below here.
			///////////////////////////////////////////////////////////

			}
			$i++;
		}

	}
}

?>

Note the area in the function where you can edit your image tag and/or link code to suit your own needs.

Then place the code below in the post loop of your WordPress theme where you want your images to show up:

<?php
/* And here is the php code you'd put in your WordPress Theme:

nerdy_get_images('medium','0','0'); 

There are three settings: nerdy_get_images([SIZE OF PREVIEW],[NUMBER OF IMAGES TO SHOW],[OFFSET FROM FIRST IMAGE]); 

[SIZE OF PREVIEW] = can be either 'thumbnail' or 'medium'. Defaults to 'thumbnail'.

[NUMBER OF IMAGES TO SHOW] = Max number of images you want listed from the post.
It will max out at the total number of images attached to the post. Defaults to showing all images.

[OFFSET FROM FIRST IMAGE] = Lets you start at image 2, 3, etc.
Useful for distributing images around your post.
Example: You can call <?php nerdy_get_images('medium','1','0'); ?> before your wordpress content to print 1 medium image before your text to use as a teaser, then call <?php nerdy_get_images('thumbnail','0','1'); ?> below your content to print the rest of your images as a thumbnail gallery.

Note: The [OFFSET FROM FIRST IMAGE] number overrides [NUMBER OF IMAGES TO SHOW].
Example: Say your post has 10 attached images. If you call nerdy_get_images('thumbnail','8','6'); the function will only return images number 7,8,9,10 (4 total images) since you told the function to start at image number 6. This is simply because you've run out of images to print before you reach the number you requested.
*/

?>

I’ve included some documentation in the code chunk above to help explain how to use it.

Examples / Demos

Charlotte Newborn & Children’s Photographer Ashley Gillett uses a newer and more robust version of this function on the site I recently built for her:

See the function being used at Ashley Gillett Photography.

I also recently began using this function to handle image insertion on CraigsLiving.Com, a site where I post stuff I have for sale on Craig’s List:

Here is another example of the function in use.

In this case, I have it insert the first image attachment above the post content, then insert all the other image attachment below the post content. Here’s an extremely basic example of how to do this in your WordPress theme:

<!-- Start the Loop. -->
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

<!-- Display the Title. -->
<h2><?php the_title(); ?></h2>

<!-- Display the Post's First Image Attachment. -->
<?php nerdy_get_images('medium','1','0'); ?>

<!-- Display the Post's Content. -->
<div class="entry">
<?php the_content(); ?>
</div>

<!-- Display the Post's Remaining Image Attachments. -->
<?php nerdy_get_images('medium','0','1'); ?>

<!-- End the Loop. -->
<?php endif; ?>

This function has proven to be extremely helpful as well as a huge time saver for me and my clients. I hope it’s helpful to you as well!

Comments

  1. robin says:

    SO AWESOME!!! Thank you so much for this! I’ve been searching literally ALL day on a good way to include JUST a certain number of thumbnails in my “main page” to conserve space (the reason being that it’s actually a custom website that calls to WP, instead of a custom website built within WP’s restrictions.

    however, i have one question that i’m sure is easy. I’m actually VERY VERY new with php so i apologize in advance.

    How would i go about linking each thumbnail to their original (fullsize) URL

  2. Cory says:

    “Hackamojo™ brand PHP” – Good stuff – thanks for sharing your code – C

  3. Thanks!

    I used your code as a base to create a small visual treat with WordPress gallery features, PHP and jQuery. I go through the process in my blog: http://www.sanaracreations.fi/web/script-to-create-a-custom-random-gallery-in-wordpress-and-using-jquery-to-design-the-layout