How to Create Image Galleries in Your Theme
116WordPress 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | // Assuming we found some images, display them. if($images) : ?> <div id="images"> <h2>Image Gallery</h2> <ul> <?php // 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) : ?> <li<?php // 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'); ?> </a> </li> <?php endif; $count++; } ?> </ul> |
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.
1 2 3 4 5 6 7 8 9 10 11 12 | <?php // 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 »</a> </p> <?php endif; ?> </div> <?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!
I’ll definitely have a go at this. Great article.
Awesome, let me know how you get on!
Nice image gallery tip, I’m going to give it a try on my blogs
nice tips, will give this a go when I have the blog area of my site up and running!
Excellent topic Michael, would be awesome if you can include the demo IMHO. And please keep writing, we, readers appreciate a good content from you.
Btw, may I suggest you to check out MonokromePlus, an ‘Image-Gallery-Lover-Best-Friend’ and super affordable WordPress theme. Now with Flickr Photoset support ツ http://demo.themebaker.com/#theme=monokromeplus
Apologize in advance if this may looks a bit off-topic.
Ahahahah.. I am happy with the result. I just apply the code and put it on. And my template and layout now is so adorable. It is fantastic, I am trying to put some details on it to improve it. Thanks!
Under Step 1, you say “Below that line, paste the following:” but there’s only text following that references something that’s obviously missing . . .
+1
+1
Sorry guys, thanks for letting me know about the error! Fixed that now!
Thanks for correcting the tutorial. I was having problems trying to figure out what to paste, and then I returned to this site today, and noticed the update.
+1
@Michael: I’m neutral about follow or nofollow, but I did notice you promote “(We DoFollow)” while comments made on this article all have ‘external nofollow’ on them ;-)
You have to have written 2 comments on the blog to get the nofollow removed.
very usefull post thanks a lot
Welcome! :)
Could you possibly post a demo of this tutorial in action? I’d love to see it!
Thanks
Sure thing, I was thinking of that at the time. I think keeping a WordPress install for each of these tutorials may be over the top, but perhaps a quick video to show the outcome would work? What do you think?
Agreed. A quick video would be great. Looking forward to it :D
I’m currently using a plugin to run an image gallary but would like to remove it, so will try your little guide here. I’d rather not have the gallary plugin as it takes a lot to run on my server. :)
That’s awesome Dean, would love to see it when you’re done! Let me know if you have any troubles!
Hei..Thank u very much for this post..i was looking for that kind of gallery with a plugin or something like that…but this is much better Michael.
10 Points !!
Byee :)
No problem Maxi! It’s great to hear you liked the post! :D
This is exactly what I’m looking for. I will apply it right now. And, how about the slideshow in the title bar?
Creating image gallery looks simple now. I have try the code tonight and see whether I am able to get it. Anyway thanks for sharing Michael.
Also Michael Why these days there are only one or two posts per month. I love your blog so much. Write more.
You’re totally right there. My posting rate has been abysmal the past few months. I’m trying to fix that now (starting off with one a week, and see how it goes from there. One step at a time I guess!). Writing this week’s post now. I really would like to get back to writing regularly, I’ve really started to miss it :(
Thanks for your support though. It’s pretty awesome to find that someone enjoyed the blog enough to notice the decline! Thanks for bearing with me through it, I’ll have it back to life soon, I promise!
I check regularly as well and would certainly appreciate more frequent posts as well :D Just some points of motivation if you needed any :)
Good luck and happy holidays (while I suffer miserably and take my final exams, UGH!#!@)
Really nice tutorial this.
Great for anyone actually creating new themes as well as editing existing ones.
Nice work
Thanks Adie, really pleased to hear you enjoyed it! :)
Congrats with another great tutorial Michael!
The only thing i really miss it’s a demo to look at the final result :( – anyway it’s awesome!
Thanks for the feedback Stellan. I think you’re right about the demo; that’s definitely something I should put up. I always write the code for these tutorials locally to make sure it works, makes no sense not to put the showcase online as well I guess!
Hi Michael
Well set out article – you might even tempt me into trying a little PHP.
Perhaps that should be my new year’s resolution. To overcome my fear of PHP.
Merry Christmas.
Merry Christmas Keith, I hope you have a good one!
Haha, PHP can be fun. I guess one nice part is that if you make a big mistake, then it usually tells you exactly what error you made it on (And it’s usually that you’ve left out a bracket or something :D )
Hmm… New Years resolutions. Uh oh. I didn’t do too great with my set from last year… :(
I am newbie. I have taken start from HTML and by master this I will sure go for PHP.
Will have a go at this for my new portfolio. Think it could work very nicely. Thanks for the guide Michael Martin.
Rengøring
Nice tutorial, there are also some plugins that can do this but I like to build and customize things myself.
At the moment I don’t have the time to try it, but I think I will when the Christmas holliday starts.
Michael, thanks for a wonderful post. I can’t tell you how helpful problodesign has been to be and my education of web design. Thanks again. Jeff.
Great info, just thought of an excellent idea in showcasing infographs on my homepage. Thanks for sharing!
Very useful stuff. I will bookmark it .
oh,it’s beautiful,maybe i can add it to my site(digfree.tk):D
Thanks for the article, I would like to see a demo of this tutorial in action.
your article is interesting. thank you for sharing this info:http://www.all-laptop-battery.co.uk
oh it’s great!
can i translate it into Chinese ?
Sweet, but my blog theme already have a neat preview jquery. :)
love this tutorial…
even I have to learn more about this….
thanks again…
regards
I’ll have to sit down and try to understand this a little better. Right now it’s going over my head…
Wow, this looks really awesome. I believe my blog post will look more interesting and definitely more pro-look with a beautiful mini gallery like that! Will read the details to see how to really implement it on my blog!
Thanks for this post. Since my site is a WordPress site, I am going to apply this on my website.
informative post, thanks for sharing a good tutorial
one question though, as i’m using thesis theme could you help me out in adding image gallery in it??
Great tutorial. Very clear. I was looking for the right way to add a counter within the loop in order to be able to generate anchor references for a table of contents that links to excerpts within the same page. Thanks.
This was really useful, thank you. I’ll definitely use this tutorial on my site.
hello,
Allow me to ask something.
in this tutorial, you want to show image gallery is taken from a blog post, right?
How about if I want to build a picture gallery which is not derived from any post? I mean for example, may be image that is displayed in the gallery are taken directly from the wordpress image library. is it possible?
sorry about my english. thank you very much:)
Hi Michael, thank you for this post. I really love the flexibility of PHP and of course WP is a blessing to us peeps who is not super gifted when it comes to page development.
Hope to see tutorials about how to make your WP mobile friendly, I think that would be interesting.
Happy Holidays!
thanks for this great tutorial, i’ll try on my blog. Happy holidays
What a great tut! Thnx for posting!
Really good tutorials!
Great script. I used it on my blog, but I’ve made some changes. If you allow – I can post an updated script here.
Very practigal and great. Thank you.
Good post have been looking around for something like this for a while!
Great Function, thanks.
Try to do it later.
Thank you very much Michael, your guide is pretty straightforward and work like a charm!
great article – thanks a lot)))))) got a lot of useful information form here)))
Thanks for sharing. The guide is pretty straightforward
I call it Awesome !!!! :)
Great tutorial. will try to make this gallery in my theme.
This is wat i am looking for a long time. I ve got a good idea on how to create image galleries.
Nice code there buddy. I myself didn’t know how to make a theme out from my images.
Nahh .. this is great tutorial, save page as :)
This is the code that can exactly help for me for theme
Wow, we sure will make use of the tutorial soon. we plan a gallery of character which did not make it into the book.
best,
achim
Great tutorial. Very clear. I was looking for the right way to add a counter within the loop in order to be able to generate anchor references for a table of contents that links to excerpts within the same page. Thanks.
thanks for great turorial :)
Great sharing of image galleries.
At present I use plugins but hereafter I can use this code. Useful for creating new themes.
Definitely going to be using this Michael. I was having some horrible problems with the layout of my images within a wordpress blog post yesterday. They kept aligning to the left even though I wanted them to display in the centre. Along with this the text all over the place. It looked disgusting.
I did eventually resolve the issue by adding a caption to the image upload. However this gallery will bring something new to my posts when I’m uploading a number of images within a post. Good work!
Hi Michael.
Another excellent tutorial!
I tried to submit on designfloat.com (just registered), but I found their whole process really tedious and error prone.
I gave up for now.
If you know them, tell them they’ve got to make it easier for people!
Really nice tutorial this.
Great for anyone actually creating new themes as well as editing existing ones.
Nice work
thanks for great turorial
That’s pretty good and very innovative idea. thanks for sharing the code.
this is good…. but after inserting it blog loads slowly
Micheal. Great article. Thanks.
Really cool variation to embed the images.
Another plugin that you replace with your code.
Thx for sharing this tutorial.
Thanks for this, as good as WordPress is (and it is good) images can be somewhat of a pain to administer and place where you want.
Everyone seems to be looking for a method or plugin to allow gallery usuage in their theme. With this handy little tutorial it will allow them and me :-) to actually do it! Rather than searching the WP Plugin directory and trial and error which one works which one doesn’t etc.
Thanks for this bookmarked it!
Cheers
Ben
This i was looking for and now i got it so i am going to make gallery for my photography work on my blog.
Thanks for correcting the tutorial. I was having problems trying to figure out what to paste, and then I returned to this site today, and noticed the update.
Thanks I need to add an image gallery and this tutorial is gonna save me quite a bit of time in figuring out how to do it myself.
Okay, I thought this was going to be really difficult to follow but no, you have explained everything so clearly. Thanks so much for the tip and the heaps of detail you have provided for designers and technophobes alike :)
The tip to add the image dimensions is very good. I deal with a lot of busy blogs (millions of page views per month). One of the first things I encounter is the failure to optimize images and set their size in the code. Setting the size improves rendering time as the browsers know how much space to reserve for the image.
It will be great if you could have a tutorial to create a portfolio
Thanks
thanks for this informative tutorial with code about image gallery creation. i will try it in my blog site as per your steps you have described here.
Well this tutorial is great, but I don’t want to change any code. Do you have any good plugin that can install a jQuery enable Photo gallery on my website with less effort.
Excelente recurso.
Vou testar no meu site.
This is a very useful article. Although a few good plugins are available, this makes customizing galleries easier. Esp, for people like me who have lot of images on their blogs, this is really quite handy.
I check regularly as well and would certainly appreciate more frequent posts as well :D Just some points of motivation if you needed any :)
thank you for this information code tutorial on creating a photo gallery. I will do my blog site as per your steps that you described here.
Very nice tutorial. It is image link to attachment page or not? How to make image link to attachment?
it is very useful!!!
very helpfull n usefull
keep posting brother.!!
I am getting an error : ” Fatal error: Call to undefined function get_post_thumbnail_id() in /home8/grillin1/public_html/demo/wp-content/themes/newswire/functions.php on line 190″ suggestions??
Hi Michael! Thanks very much for this tutorial. I was able to change the function a little and use the unordered list in a Pikachoose slide.
You can see the code here – http://rozanchetta.wordpress.com/2011/08/24/slide-pikachoose-sem-plugin/ – it’s in portuguese.
Regards from Brazil!
nsightful thoughts here. Are you certain this will be the best way to look at it although? My encounter is that we should pretty much live and let live because what one person thinks just another person simply doesnt. Individuals are going to do what they wish to do. Within the end, they always do. Probably the most we can yearn for is to highlight a few issues here and there that hopefully, allows them to create just a little much better informed decision. Otherwise, fantastic post. Youre certainly making me believe! Barry
well done bro i love you.. very nice tip on gallery without any plugin. thankss
thanks for the detailed information.
I followed step by step and it worked like a charm.
Image galleries are always a plus .
Thanks for sharing
Wow, we sure will make use of the tutorial soon. we plan a gallery of character which did not make it into the book.
best,
Hello,I think it is good blog,I added at my favorite.Best wishes!
This is one of the great blogs I’ve read today. Your site contains lots of good information and I’m sure many people will like it as I do. I would like to give this site a thumb up rating. Keep up the good works guys. I think I’m going to come back to this site regularly. Thanks.
I must say I’m so glad to find your blog, even though I did it by a fluke. The information posted here is so entertaining and different to the other blogs. In short, a really nice blog that I’ll keep visiting very often.
ive been doing some stuff for my mums business in my free time (not advertising just saying!) and i always appear to be a constant battle with wordpress, not anymore lol !
Keep up the good work!
its work properly. good tutorial. thx for sharing
Outstanding, what an amazing way to convey your current thoughts and opinions? Cool I must say? I do think you’re correct. Hope to read more write-ups from your end and I am seriously looking ahead for it.
How can I use prettyPhoto with this code?? thanks for any help.
Thank you very much for this ! I don’t have many knowledge in PHP but I could manage to combine the gallery with a lightbox effect. I’ve changed this line:
<a href="ID); ?>”>
to
<a rel="lightbox[group]" title="" href="ID); ?>” >
Lightbox needs the storage adress in uploads and not the permalink. It works very fine. But would you have an idea how I could get the title of the images so that Lightbox show a caption ? The need just a “title” for doing that, I tried some things but it doesn’t work.
Thank you !
I have it (after 2 hours… That’s the problem when you’re learning by doing) ! I just add:
title=”ID); ?>”.
Thank you again
Yeah Martin, you have given nice tips and I am very happy with the tips and by using these steps I have created the image gallery on the theme with the easy way. I like this tips very much.
It it is done like this, it will look so attractive and it will definitely catch more visitor if it is used on WordPress for blogging purposes. The first thing you need to realize is that with the introduction of this feature a new template was added to the WordPress core: image.php. If your theme is lacking this template, the gallery feature will still work, but not to its best advantage. Blog Almighty has the best instructions I’ve found for creating this template if it isn’t included in your theme.
Howdy! Do you know if they make any plugins to help
with Search Engine Optimization? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good results.
If you know of any please share. Cheers!