WordPress Image Attachment Gallery (Revisited)

As promised but long overdue, here is the followup to my original Make A Custom WordPress Gallery from Post Image Attachments post. Unfortunately I don’t have time to formulate a witty monologue to accompany this version, nor the time to go into great detail about the changes. This newer version gives you greater control over how WordPress post image attachments are formatted when the function creates galleries from them. You’ll find ample supporting information in the original post and I’ve included (hopefully) easy to understand notes in the code under the “Usage and Notes” section:

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 updated function:

// Add the ability to use post thumbnails if it isn't already enabled.
// Not required. Use only of you want to have more than the large,
// medium or thumbnail options WP uses by default.

if ( function_exists( 'add_image_size' ) ) add_theme_support( 'post-thumbnails' );

// Add custom thumbnail sizes to your theme. These sizes will be auto-generated
// by the media manager when adding images to it on a new post.
if ( function_exists( 'add_image_size' ) ) {
	add_image_size( 't1x1', 145, 200, true );
	add_image_size( 't2x1', 307, 200, true );
	add_image_size( 't2x2', 307, 417, true );
}

///////////////////////////////////////////////
//
// Start WPOutfitters.com Custom Galley Function
//
//////////////////////////////////////////////

function wpo_get_images($size = 'thumbnail', $limit = '0', $offset = '0', $big = 'large', $post_id = '$post->ID', $link = '1', $img_class = 'attachment-image', $wrapper = 'div', $wrapper_class = 'attachment-image-wrapper') {
	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 $attachment_id => $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_page = get_permalink($image->ID); // The link to the attachment page.
			$img_alt = get_post_meta($attachment_id, '_wp_attachment_image_alt', true);
			if ($img_alt == '') {
			$img_alt = $img_title;
			}
				if ($big == 'large') {
				$big_array = image_downsize( $image->ID, $big );
 				$img_url = $big_array[0]; // large.
				} else {
				$img_url = wp_get_attachment_url($image->ID); // url of the full size image.
				}

			// FIXED to account for non-existant thumb sizes.
			$preview_array = image_downsize( $image->ID, $size );
			if ($preview_array[3] != 'true') {
			$preview_array = image_downsize( $image->ID, 'thumbnail' );
 			$img_preview = $preview_array[0]; // thumbnail or medium image to use for preview.
 			$img_width = $preview_array[1];
 			$img_height = $preview_array[2];
			} else {
 			$img_preview = $preview_array[0]; // thumbnail or medium image to use for preview.
 			$img_width = $preview_array[1];
 			$img_height = $preview_array[2];
 			}
 			// End FIXED to account for non-existant thumb sizes.

 			///////////////////////////////////////////////////////////
			// 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.
			?>
			<?php if ($wrapper != '0') : ?>
			<<?php echo $wrapper; ?> class="<?php echo $wrapper_class; ?>">
			<?php endif; ?>
			<?php if ($link == '1') : ?>
			<a href="<?php echo $img_url; ?>" title="<?php echo $img_title; ?>">
			<?php endif; ?>
			<img class="<?php echo $img_class; ?>" src="<?php echo $img_preview; ?>" alt="<?php echo $img_alt; ?>" title="<?php echo $img_title; ?>" />
			<?php if ($link == '1') : ?>
			</a>
			<?php endif; ?>
			<?php if ($img_caption != '') : ?>
			<div class="attachment-caption"><?php echo $img_caption; ?></div>
			<?php endif; ?>
			<?php if ($img_description != '') : ?>
			<div class="attachment-description"><?php echo $img_description; ?></div>
			<?php endif; ?>
			<?php if ($wrapper != '0') : ?>
			</<?php echo $wrapper; ?>>
			<?php endif; ?>
			<?
			// End custom image tag. Do not edit below here.
			///////////////////////////////////////////////////////////

			}
			$i++;
		}

	}
} 

///////////////////////////////////////////////
//
// End WPOutfitters.com WP Custom Galley Function
//
//////////////////////////////////////////////

Usage and Notes:


// Example call with all arguments:
wpo_get_images('thumbnail','0','0','large',"$post->ID",'1','attachment-image','div','small-thumb');

/*******************************************
Explanation of the arguments passed to the function:

wpo_get_images(
[preview_size], // See note 1
[number_of_images_to_show], // See note 2
[offset_from_first_image], // See note 3
[big_image_size], // See note 4
[post_id_to_get_images_from], // See note 5
[link_to_large_image], // See note 6
[image_class], // See note 7
[html_wrapper_tag], // See note 8
[html_wrapper_class] // See note 9
);

Notes:

1. The size of the WP produced thumbnail you want displayed. WP gives you 4 choices by default: 'thumbnail', 'medium', 'large', or 'full'. Using the add_image_size function in your functions.php file you can add your own sizes. This function defaults to 'thumbnail'.

2. Max number of images you want displayed for this call to the function. It will max out at the total number of images attached to the post. Defaults to showing all images.

3. Lets you start at image 2, 3, etc. Useful for distributing images around your post. The number here can override the numb roof images to show. Example: Say your post has 10 attached images. If you set this to 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.

4. The size of the large image you want to link to. Can either be 'large' or 'full'. Setting it to large will link to an image that WP resizes in accordance to what you set your large image size to on the media settings page. Setting it to 'full' will link to the untouched image you uploaded.

5. The post ID you want to show images from. Useful if you want to grab images form another post or want to set up a portfolio type thing. Defaults to the current post's ID ("$post->ID"). Remember to use double quotes when setting this one!

6. Whether or not to link to a large image. 0 = no, 1 = yes. If set to no, it will just display your chosen images set in [preview_size] without linking to bigger ones.

7. Name of the css class added to the image tag. Defaults to 'attachment-image'.

8. Type of html wrapper to enclose each image and all of it's related code in. Defaults to 'div'. Can also be 'ul', 'p', 'span', etc.

9. The css class assigned to each [html_wrapper_tag]. Defaults to 'attachment-image-wrapper'.

More notes: 

- In the media manager you can set the image's alt and title for each image. 

- If you choose to set a caption for an image, it will be displayed below the image and wrapped in a div called "attachment-caption".

- If you choose to set a description for an image, it will be displayed below the image and caption and wrapped in a div called "attachment-description".

*******************************************/

Cheers!

Comments

  1. robin says:

    thank you so much for your quick reply! can’t believe i didnt notice that link to the updated version RIGHT UP there.

    you can check out my progress/implementation here http://sonark.com/homepage.php

    awesome!!!

  2. Thanks for sharing. A couple of questions:

    1. Does the function call have to be in the “loop”?
    2. The “t1x1″ argument doesn’t seem to take. Only the WordPress defaults of thumb, medium, etc. works. Any ideas?

    Thanks again!

    BTW – I’m using Thesis 1.8

    • Dameian says:

      David -

      1. No sir! You can call it anywhere you please as long as you pass a valid post ID to argument #5 one way or another.

      2. The t1x1 is just an example for using add_image_size(). You’d have to first set that up in your Thesis custom_functions.php with:

      if ( function_exists( ‘add_image_size’ ) ) {
      add_image_size( ‘t1x1′, 145, 200, true );
      }

      Then upload some images to a post. It will only work for images added to posts *after* your new t1x1 add_image_size is set because WP doesn’t retroactively create thumbnails for newly set sizes.

      One you do that, then the t1x1 size example should work as long as everything else is set up correctly.

  3. Rudi van der Merwe says:

    Hey! Thanks bro, I’m using your function, u just made my life much easier….

    maybe it is just me, but for some reason the php tags weren’t playing well in my functions file, it gave me a php syntax error, so I removed the tags and replaced it with echo’s, all is working well now…. also it seems the link to the older version, at the top op this page, has died.. and the link to the new version, at the top of the older version, has also died….. takes me a 404 on dameian.com

    Thank you!

    • Dameian says:

      Ah – yeah. These posts were moved over from dameian.com and I apparently neglected to update the urls. Fixed now. Thanks for pointing that out to me!

      RE: php tag errors… no idea why that would have happened. I’m glad you got it working though!

    • Hi.
      It’s great, I was looking for something like this a long time for using as a portfolio gallery.
      You can take a look at my implementation here pauloramalho.com/diseno/portafolio-web. It’s not done yet so I use to have the maintenance plugin activacted.
      Thank you very much for sharing your work Dameian.
      Best regards.

  4. David Bell says:

    Hi Dameian, thanks so much for sharing this code. Really helped with a theme I’m busy building. Was really struggling with being able to call the images from any post.

  5. Hi!
    I still discovering the power of this gallery (the gallery custom sizes are amazing) and have a question! It’s possible to override the WP image URL to a custom one? Let’s say, a link to a page.

    • Phillip says:

      I think this code is awesome. Similar to Paulo’s request. How would you link the thumbnail to its post.

      • Dameian says:

        @Philip

        The brute force way would be to replace this line:

        <a href=”<?php echo $img_url; ?>” title=”<?php echo $img_title; ?>”>

        with:

        <a href=”<?php echo get_permalink($image->post_parent); ?>” title=”<?php echo $img_title; ?>”>

  6. Nunsuch says:

    Thank you *so* much!

    After 4 years of struggling to train my web design customers to create web galleries in WordPress posts/pages, I’ve finally given up. It just can’t be done. (The person I’m working for now has a tendency to bang on his keyboard if things don’t go his way, right away… And I do admit that WP has a terribly complicated back end. Sigh.)

    Along came the WP custom posts types, and than I found your article – a badly needed missing piece that makes WP as CMS come together in a way that would make it easy for a bad tempered 5 year old to create good looking content. Awesome!

    …And thank you for your sense of humor. Found your site at 3am, and a bleary 16th work hour, and you made me both laugh out loud and learn.

  7. ArgentOunce says:

    Thanks for sharing such a useful solution. Customizing wordpress galleries is such a pain and your function is a killer one. Amazing work, I’ll be back shortly to show you the implementation. Greetings from México.

  8. Alvin says:

    Dameian, thanks so much for making this tutorial, I have been scouring the web hgih and low for something like this. How do we make it work on attachments.php/the page of attachments themselves though?

  9. Dameian says:

    @Alvin – Do you mean attachment.php? The short answer is you wouldn’t use this function in that template. Attachment.php’s purpose is specifically to display one single attachment image. This function is designed to automatically generate galleries within posts. Two very different things.

  10. Zuri says:

    Hi Dameian,

    Thank you SO much for this fantastic tutorial! It’s exactly what I was looking for. I do have one problem though. I’m using your function to display images as full screen backgrounds. The correct images are showing, however, for some reason they are being re-sized to 150x150px. Therefore, when they get stretched to full-screen, they are incredibly pixelated. Is there something in the function that I’ve missing, or is it in my own code?

    Cheers,
    Zuri

    • Dameian says:

      It has a built-in fail safe. If you try to call an image size that doesn’t exist, it defaults to the WordPress thumbnail as defined in the WP Admin under the media settings. It looks like that is being triggered here.

  11. Andrew says:

    Thanks so much for sharing this Dameian. I have been looking for a simple and elegant way to build a gallery out of the images attached to the post and this is by far the nicest implementation I have come across.

    At the moment I have all the images at a thumbnail size. Is there any way to make the very first image a different size than the rest? say a medium size? I’m planning on having the first image a bit larger than the rest so it looks a bit nicer. Clicking any of the images just pops up a lightbox.

    • Andrew says:

      Cancel that Dameian. Just realised I could use two calls and use the offset feature you have there. Love it, thanks again :)

      //Grabs just the first image at medium size
      ID”,’1′,’attachment-image’,'li’,'small-thumb’); ?>

      //Grabs just the rest with an offset of 1
      ID”,’1′,’attachment-image’,'li’,'small-thumb’); ?>

  12. david says:
    • Dameian says:

      Yep, it can be used to populate just about any script like this. You’d just have to edit the function to replace the anchor tag with what ever code you need.

  13. Dameian,

    First of all thank you for this function.. It is really amazing of simplicity on the user side, so it’s quite worthless..
    Now I was wondering, did you think of adding the js masonry to the display of the images?
    It would be quite amazing..
    I’m not a developer so I have some difficulties to find out how to do that myself, but I’m trying…
    Here is the link to the script if you’re not familiar with it: http://masonry.desandro.com/demos/images.html
    I think it would be great because it allows to have images of the same width and different height in the same column…

    Keep up the good work.
    Fab

    • Dameian says:

      I’m very glad to hear that it is quite worthless to you! Of course I’ll do free custom development and integration work for you that my clients pay $70/hr for. Keep checking back. It will be posted soon. I promise.

  14. david says:

    How do you remove the images that have been uploaded that appear in the body of the post – do you need to delete the image code from the Loop? – so you don’t get duplicated images. (Sorry, I’m a WP novice.)
    or do you just delete them from the post area.

    Also, how do you remove an image from a post ? it seem to stay there even if it has been deleted from the post body. Do you need to delete the whole post and create a new one?

  15. david says:

    Could you explain the correct process in using the script – do you upload images or gallery which will make the images appear in the post body, but then delete them, so you don’t get duplication as they will appear in the loop+ your custom code. And then if you edit the images later you need to go to the media library and delete and re-assign a new image if required?

    Or is it best to delete the images area of the loop template so the images appear in the post body. Although if you delete one it will still appear unless you delete it from the media library? Confused.

    • Dameian says:

      This function grabs any images attached to a post and automatically display them how you set it up to. You do not put images in the post content area if you use this function. I created this specifically so my clients didn’t have to waste their time doing that. The two are mutually exclusive and will of course cause duplication. Honestly if this is giving you trouble, this function probably isn’t the solution you’re looking for. It is designed to aid developers who are building custom galleries and such for clients.