WordPress makes it straightforward to create a gallery from the images attached to a post. Just a couple of clicks and the gallery shortcode will be inserted into your post for you.

Why not make it even easier though? In this post, I will walk you through adjusting your theme to automatically insert a gallery after every post.

We’ll also limit how many images show up in the gallery (The rest can be shown on the individual image pages themselves), and exclude our post’s featured image if it has one.

1 – Editing the Template

We will be editing 3 of your template files in this tutorial:

  • Single.php – To insert the gallery after your post.
  • Style.css – To format it nicely.
  • Functions.php – Where we will put the code that creates our gallery.

In the example, I’ll be working through with the default 2010 theme, but the steps are identical for any theme.

Let’s start out by opening up single.php. Now search for the line that says the_content()

Below that line, paste the following:

<?php pbd_image_gallery(); ?>

This is simply a call to the function we are going to create in functions.php now (The 3 letters at the start are to make sure no other plugin is already using that function name, feel free to rename it if you wish!)

2 – Building Our Function

The pbd_image_gallery() function is going to look at the post we’re currently on, find out what images have been attached to it, and then display them all in a list for us to style.

We will start out by creating the query we will need to run to find the images on the post. In functions.php, paste the following at the bottom of the file (Before the closing ?> tag):

function pbd_image_gallery() {
	global $post;
	$limitImages = 8; // How many images in total to show after the post?
	$perRow = 4; // How many images should be in each row?
	$featuredID = get_post_thumbnail_id($post->ID);
	// Build our query to return the images attached to this post.
	// We query one image more than we intend to show to see if there extra images that won't fit into the gallery here.
    $args = array(
        'post_type' => 'attachment',
        'post_mime_type' => 'image',
        'numberposts' => $limitImages + 1,
        'orderby' => 'menu_order',
        'order' => 'ASC',
        'post_parent' => $post->ID,
        'exclude' => $featuredID
    $images = get_posts($args);

The first line is simply declaring that this is a function. We then grab the $post variable (Which contains information about the current post, like its ID) and set some preferences (How many images to show in the gallery in total, and how many will be in each row).

On line 7, we use the get_post_thumbnail_id function to find the ID of the image being used as the thumbnail. We then later use this information on line 18 to make sure that the featured image is not part of our results.

The rest of the lines are our query. The get_posts() function we have used is a simpler alternative to a full-blown WordPress post loop. Each image found will be stored in the $images arrayed, allowing us easy access to things like the image ID.

3 – Outputting the HTML

Now that we have our images in PHP, it’s time to spit them out into the HTML as well. Paste the following directly below the code from above:

// Assuming we found some images, display them.
if($images) : ?>
<div id="images">
<h2>Image Gallery</h2>
    	// We'll use the $count here to keep track of what image we're on.
    	$count = 1;
    	// Print each individual image.
        foreach($images as $image) { 
        	// Only show the image if it is within our limit.
        	if($count <= $limitImages) : ?>
	        	// Each end image in a row gets the "lastimage" class added. 
	        	if($count % $perRow == 0) { echo ' class="lastimage"'; } ?>>
	        	<a href="<?php echo get_permalink($image->ID); ?>">
	            	<?php echo wp_get_attachment_image($image->ID, 'gallery-thumbnail'); ?>
         } ?>

This code first checks to see if we found any images (If we didn’t, then it will do nothing).

It then outputs some basic HTML (A div to identify our gallery by, a headline, and the start of our list).

The fun starts on line 7. We begin by creating a variable called $count which we will increment after each image (Line 25). This variable will keep track of which image we are on.

We use line 12 to create a loop which will cycle through each of the images in our results. For each image, we will check that we haven’t yet hit the image limit, and then display it (linked to the larger version on the image’s own page).

Later on when it comes to styling our gallery, it may be useful to have a CSS class on each of the last images in a row. To that end, we use lines 15-17 to see if the current image is a multiple of our number of images per row.

The wp_get_attachment_image function allows us to use the image ID to get the image itself, and display it. It even lets us set the size. In this case, a “gallery-thumbnail” image size that I have added by including this line at the top of my functions.php file:

add_image_size('gallery-thumbnail', 145, 145, true);

The image ID is treated exactly like a post ID, which is why I’m able to use the regular get_permalink() function to make the link to the image’s page.

The last few lines just close off our HTML and loop.

4 – Adding a “More” Link

You may have a dozen images attached to a post, but only want to show the first 8 on the post itself. We’ve already set up the functionality for that in our query above, so all that is left now is to check if the total number of results returned was greater than our limit, and if it was, link to the first image.

	// Did we have more images than our limit? Then create a "More" link.
	// This link goes directly to the first image.
	if( count($images) > $limitImages) : ?>
	<p class="photo-more">
		<a href="<?php echo get_permalink($images[0]->ID); ?>">View More Images &raquo;</a>
	<?php endif; ?>
<?php endif;

If you wanted to link to the first unseen image, then you would change the $images[0] to $images[$limitImages].

(The final few lines above close off an if statement and function, both of which were declared in other steps) .

5 – Styling Your List

The final step is adding some simple styles to make your image line up neatly. In your style.css file, paste the following:

#images ul {
	list-style: none;
	margin: 0;
	height: 1%;
	overflow: hidden;
#images li {
	width: 145px;
	height: 145px;
	float: left;
	margin: 0 20px 20px 0;
#images li.lastimage {
	margin-right: 0;

You will need to adapt some of the numbers to your own theme. In my case, I was using the default 2010 theme whose content area is 640px wide. I wanted to have 4 thumbnails per row, and 20px between each one, so 640 – (three 20px gaps) = 580px. Then 580px divided by the 4 images left 145px for each image.

Specifically setting the width and height of each list item as the size of the image is good in case a thumbnail ever is not resized correctly. This way, even if the image is a little small, it will still line up perfectly.

And that’s you done!

Taking it From Here

The next step would be to add the complete gallery (With no limit) to each of the image pages. It’s very simple to do, just use our exact same loop from above, but in the query, change your parent line to:

'post_parent' => $post->post_parent,

Let me know how you get on with this tutorial, and if you have any questions or suggestions, just post in the comments!

Enjoy this post? You should follow me on Twitter!