Galleries and images are not new to WordPress. Gallery plugins existed long before WordPress had enhanced media functionality of it’s own. The [ gallery ] shortcode was introduced in version 2.5 and the Gallery Post Format came around in 3.1. This post will walk you through the process of working with and styling the native WordPress galleries and the gallery post format.
WordPress Galleries and the Gallery Shortcode
As mentioned earlier, the shortcode was introduced back in version 2.5 but we’ll be working in 3.1+ and there really is no easier way to insert a gallery into your post, especially with the visual editor and the media manager.
Hit Add an Image when editing a post as you would usually do to insert a single image, then upload a few images (you can use the mult-file Flash uploader for this) and hit Save Changes. You’ll be taken to the Gallery tab and if you scroll down underneath your images list, you’ll see the Gallery section.
As soon as you hit the Insert gallery button, a shortcode will be inserted into your post. The shortcode itself looks like a big image space in the visual editor, but if you open up the HTML view of your post, you’ll find something like this:
[ gallery link="file" columns="4" orderby="title" ]
Please not that I add additional spaces to the short code just for illustration purposes. Yours should be without the spaces, otherwise it will not get processed by the WordPress shortcode engine.
If you preview the post in the Twenty Ten theme you’ll end up with something similar to the screenshot below.
And you’ll be taken to the attachment pages or the image files according to what you chose for your gallery settings. This is neat isn’t it? It literally takes a few seconds to upload and insert images to your post and Twenty Ten does a good job at styling the grid for you. I’ll show you how to do that in your own theme in a sec, but now on to post formats.
The Gallery Post Format
Post formats were introduced in WordPress 3.1 and under the hood it runs based on the taxonomy engine, but you don’t really need to get into those details to use post formats. Just keep in mind that versions prior to 3.1 will not understand them.
In the gallery screenshot below I’ve shown you how the gallery looks when the post format is not set as a Gallery, now watch what happens with the Twenty Ten theme when the very same post is turned into a Gallery post (I also added some text to describe the gallery).
So the (not so) new post formats give you the ability to style a gallery embedded in a post differently from a post that’s meant to represent the gallery only. It makes sense, because sometimes you want to insert galleries somewhere in the middle of your post when there’s a bunch of text, videos, and more. But sometimes you’d like your whole post to be dedicated to the gallery, which is where you use the post format.
Catching Post Formats in The Loop
The whole idea behind post formats is that you can get hold of then within the WordPress Loop and output your markup differently for different post formats. A brief look at the file called loop.php in the Twenty Ten theme reveals the markup and code difference between ordinary posts and gallery posts. It starts at line 60 with the following if statement:
if ( ( function_exists( 'get_post_format' ) && 'gallery' == get_post_format( $post->ID ) ) || in_category( _x( 'gallery', 'gallery category slug', 'twentyten' ) ) ) :
The first part is the actual check for the gallery post format, while the second part (after the OR operator) is a hack for the older versions of WordPress. Rest of the code grabs the post children (images), renders the first image in the set and a “gallery contains x images” note, which is what you’ve seen in the screenshot above.
You can use this method to display post formats differently in different templates too, just like Twenty Ten does — it renders the whole gallery on the single post page, but renders and image and excerpt on the index page, which is quite cool. Imagine you published a gallery with a hundred pictures in it, you wouldn’t want to bloat up your home page with them, right?
Here’s a more user-friendly solution, dropping the support for WordPress versions prior to 3.1, with an illustration of how the block fits into the loop. Just follow through the comments to get around:
// The WordPress Loop
<?php if ( have_posts ) : ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php if ( 'gallery' == get_post_format( get_the_ID() ) ) : ?>
<!-- Layout your gallery here -->
<?php else : ?>
<!-- Layout your standard posts here -->
<?php endif; ?>
<?php endwhile; ?>
<?php else : ?>
<!-- No posts were found -->
<?php endif; ?>
Use elseif statements on line 6 to support other post formats like Status, Video, etc. The HTML comments show exactly where the different markup should go and the rest of the code is quite self-explanatory.
So now that you’ve figured out how to change the code and markup for the gallery post format, you can create your own layout for galleries displayed on your front page. In the next part I’ll show you how to use CSS to style the actual output of the gallery (i.e. the gallery shortcode).
Using CSS to Style Your Galleries
If you’re starting a brand new theme you’ll notice that WordPress will give your gallery some sort of style even if nothing’s defined in your stylesheets. That’s the default gallery style and you can use the use_default_gallery_style filter to get rid of it, from your functions.php file, like this:
add_filter( 'use_default_gallery_style', '__return_false' );
For older versions of WordPress you’ll have to do some regular expression search and replace to remove the default gallery CSS, but I’ll assume you’re using WordPress 3.1+.
After the default styles are removed, the gallery output is somewhat ugly, and if you look at the HTML source, you’ll notice that it’s laid out using the dl and dt HTML tags. The wrapper element is a div with the gallery class name, so you have easy access to all the gallery elements through CSS selectors:
/* The Gallery container (div) */
.gallery { }
/* A Gallery item container,
for 3, 2 and 4 column galleries */
.gallery .gallery-item { }
.gallery-columns-2 .gallery-item { }
.gallery-columns-4 .gallery-item { }
/* The actual image inside a container
for 3, 2 and 4 column galleries */
.gallery img { }
.gallery-columns-2 .attachment-medium { }
.gallery-columns-4 .attachment-thumbnail { }
/* A gallery image caption */
.gallery .gallery-caption { }
/* Definition lists elements */
.gallery dl, .gallery dt { }
/* Pick the second line break if two
line breaks are adjacent */
.gallery br+br { }
Most of the selectors are straightforward, the last two may seem a little bit strange, but makes total sense actually. The definition lists elements should be reset (margins) for galleries so they don’t inherit the styles of actual definition lists. The second adjacent line break should be hidden to avoid extra spacing in galleries.
Below is a code snippet for a full example of a styled gallery. Mostly taken from the Twenty Ten theme with some slight modifications with borders, shadows, padding and hover effects. You should get a general feeling of what each selector does and play around with the styles to get more control. I also removed the comments for brevity — if you need them look at the snippet above.
.gallery { margin: 0 auto 18px; }
.gallery .gallery-item {
float: left;
margin-top: 0;
text-align: center;
width: 33%;
}
.gallery-columns-2 .gallery-item { width: 50%; }
.gallery-columns-4 .gallery-item { width: 25%; }
.gallery img {
box-shadow: 0px 0px 4px #999;
border: 1px solid white;
padding: 8px;
background: #f2f2f2;
}
.gallery img:hover {
background: white;
}
.gallery-columns-2 .attachment-medium {
max-width: 92%;
height: auto;
}
.gallery-columns-4 .attachment-thumbnail {
max-width: 84%;
height: auto;
}
.gallery .gallery-caption {
color: #888;
font-size: 12px;
margin: 0 0 12px;
}
.gallery dl, .gallery dt { margin: 0; }
.gallery br+br { display: none; }
Now, the output with that sort of styling should look something similar to this:
Upon hovering on the images, their background color should turn white. Of course you have to be running a modern browser for CSS3 shadows support, though there are hacks for older browsers too, but that’s a different post. By now you should have styled your gallery exactly the way you want it to look. Make sure you test out different columns combinations, play around with captions and make adjustments to your stylesheet accordingly.
Next up is a bonus — Lightbox!
Displaying Your Images in a Lightbox
One thing I loved about the gallery plugins for WordPress is that they come bundled with lightbox scripts so there’s always a cool fade animation when hitting an image for full size display. Now the WordPress gallery doesn’t come bundled with that. Instead it gives you the choice to link the gallery items to their attachment pages (which I never learned how to use) or the image file URL.
In this section I’ll show you how to add the jQuery Lightbox plugin and make it display your WordPress gallery images. When inserting your gallery shortcode, make sure you choose to link to the image file URL and not the attachment post if you want the jQuery Lightbox to find those URLs since that’s the way it works.
Since WordPress doesn’t come equipped with the Lightbox script, you should download your own from here. Extract it in your theme folder just like it is in the archive without shuffling any directories, so the lightbox CSS file ends up in /wp-content/themes/themename/css/jquery.lightbox-0.5.css and the rest of the files accordingly. You don’t need the index.html file and the demo photos.
As soon as you’ve done that you’ll have to include the javascript and stylesheet to your theme head section via your functions.php, the easiest way is to simply append the following two lines of code to your functions file:
wp_enqueue_script( 'jquery-lightbox', get_stylesheet_directory_uri() . '/js/jquery.lightbox-0.5.min.js', array( 'jquery' ) ); wp_enqueue_style( 'jquery-lightbox', get_stylesheet_directory_uri() . '/css/jquery.lightbox-0.5.css' );
Make sure the script and stylesheet are included and the links are not broken. Then fire up your header.php file and add the following snippet right before the closing head tag. This will activate the lightbox plugin for your gallery thumbnails:
<script type="text/javascript">
jQuery(document).ready(function($) {
var images_dir = '<?php echo get_stylesheet_directory_uri() . "/images/"; ?>';
$('.gallery-item a').lightBox({
imageLoading: images_dir + 'lightbox-ico-loading.gif',
imageBtnPrev: images_dir + 'lightbox-btn-prev.gif',
imageBtnNext: images_dir + 'lightbox-btn-next.gif',
imageBtnClose: images_dir + 'lightbox-btn-close.gif',
imageBlank: images_dir + 'lightbox-blank.gif'
});
});
</script>
Save and close your header file, refresh your gallery page and try clicking on the gallery images. If you did everything right you should see a smooth popup transition with cool fade effects that will show the full-sized image that the thumbnail linked to. You can click the left and right parts of that image to navigate through the gallery and close it by either clicking outside the lightbox or on the close button on the bottom right of the box.
Here’s what it should approximately look like:
Yes, that’s a screenshot of the WordPress 3.2 release candidate in a lightbox, and I can click left or right to navigate to the other pictures in the gallery, with smooth transitions of course!
Recap & Conclusion
If you’re reading this you probably made it this far, and we’re glad you did! A brief recap — in this post I talked about galleries, about gallery plugins and about the gallery post format introduced in WordPress 3.1. I showed you a snippet of how to split the markup for regular posts and gallery posts for your front or archive pages. I went through using CSS to style the gallery output based on the Twenty Ten theme, and finally implemented Lightbox previews for the gallery items.
Now that you’re familiar with all these things go ahead and experiment with styling your galleries. Try different column layouts, thumbnail sizes or even a different lightbox script, like Colorbox or Facebox.
So do we really need all those gallery plugins for WordPress if the new standard methods are so easy to use? I guess not, especially since most of them have dropped any kind of support or updates anyways, and will eventually get deprecated.
Go ahead and show off your own gallery styles in the comments section! Use a picture service such as Twitpic or yfrog and post up the links. If you have any questions or trouble following this tutorial feel free to ask.








Pingback: Theme.fm will be a blog about fine tuning WordPress | WPCandy
Hey, Konstantin. Congrats on the new blog! I read about it from WPCandy. After reading this post, I got hooked. I’m looking forward to future posts.
I know that there are more lightbox plugins than is bearable, but the one I’ve settled with is FancyBox. It works similar to the one you suggested but is available as a WordPress plugin, which makes it a breeze to install and start using on your WordPress blog.
Thanks for your comment Tony, you made it into the history of Theme.fm, yours was the first non-spam comment ;)
FancyBox is a great suggestion, and the fact that it’s available as a plugin is great. Loving their mouse-scroll to browse the gallery feature!
I’m also using fancybox for anything. I like the fact that you can to a lot of stuff with it from videos, iframes etc… the scroll for next image feature is ok but who really uses it?
Good question Vlad, but it’s always good to know it’s there. And for us developers it’s cool because they managed to do it, not because it’s going to be used, right? Left and right arrow keys are supported as well, but I have a feeling those aren’t used either, unless it’s written there in red ;)
More trendy now with such overlay views is the mobile environments, where lightbox, facebox and fancybox are simply lagging on iPhone and Android devices (can’t speak about the latest). But my feeling is that those need special views.
A great discovery is Jaipho which displays your galleries in an iPhone-fashion — full screen and with sliding effects, gestures seem to be supported as well, although didn’t test it. Perhaps it’s a good addition to the many iPhone-compatibility plugins for WordPress out there.
Thanks for your comment!
Nice article. I read a post last month that had me thinking the same thing — why do I need a gallery plugin when WordPress has gallery functionality baked right in. Glad to know others are thinking the same thing.
Hi Jason, thanks for your comment. Yeah that post by Otto is definitely worth reading, thanks for mentioning it here!
Nice Article. Just when I was looking for something like that you hit me with a post on your new blog :)
Put me in your mailing-list!
Thanks Jannis, our mailing list is going to be something really, really awesome, but we’re rolling that out later this year since it’s a lot of work. Meanwhile you can subscribe to our RSS feed and we’ll keep you posted ;)
Pingback: Links der Woche – KW25 » Nikonierer
Pingback: Twenty Eleven Post Formats – What Are They and Why Should I Care? | WordPress News at WPMU.org
Great article and very timely for me.
What do you think of modifying not just the default styles but the default markup as well? Using DL and DT for photo galleries with hardcoded line-breaks in between each row has always struck me as really kludgy. Any advice for better markup or plugin suggestions that handle this?
Sure, take a look at the
icontag,itemtagandcaptiontagon this page. It’s not the best approach of doing that in your shortcodes but the other option would be to dig inside the gallery shortcode internals and look for filters you can take advantage of.Take a closer look at
/wp-includes/media.phpyou’ll see thegallery_shortcodefunction there. Probably not as many filters as we would love to see… I think I should submit a patch to trac :) You can still override the whole output though!~ K
Here we go: Ticket #18472 let’s see how this goes :)
Okay, turns out there’s an even better #15155 ticket dealing with shortcode attributes in general, sweet!
Is there a way to set gallery default columns for example to 2 or 4 without hacking the core? Instead of having 1 to 9 columns has set by the core.
Hi Paul, unfortunately not with the current stable, but hopefully this ticket will get closed sooner or later which would allow themes and plugins to filter shortcode attributes, that way you can override defaults for galleries, captions, etc.
Thanks for the quick reply. Good to hear that. This will be very handy if it gets implemented.
I wonder how can you style the gallery so that it displays the images in a slider, just like in this theme: http://themes.premiumpixels.com/?theme=memo
Do you have any idea?
I bet that some hardcore CSS and jQuery magic can do the trick but of course it’ll be a lot easier to just get rid of the gallery and work with the images attached to the post, like we do in our Lorenz Theme ;)
Hello,
can someone please tell me, how I can remove the links from the thumbnails in the WordPress Gallery.
No I have 2 choices to Link thumbnails:
a) image file
b) attachment page
Is it possible to “remove” this Link? When I click the image, nothing should happen.
Thank you very much for your help!
Anja
This is exactly what I need, but I can’t make it work. I copied the files to the correct directory is there any reason why it wouldn’t work?
Definitely imagine that that you said. Your favorite reason seemed to be on the web the simplest thing to bear in mind of. I say to you, I definitely get irked while people think about issues that they plainly don’t know about. You managed to hit the nail upon the highest and defined out the whole thing with no need side effect , other people could take a signal. Will likely be back to get more. Thanks
Fantastic post. I’ve been fooling around a bit trying to figure out if I wanted to use NextGen or other plugin options since I wasn’t sure if I could make the default gallery look the way I wanted. Problem solved. Thank you!
Thanks much! found exactly what I was looking for.
Awesome post!
I was looking for how to do a lightbox, and have found it, thanks to you.
Any thoughts or resources how to just add next/previous buttons on the attachment page – integrating numbering would be great too.
Hi, im trying to override the default gallery to a big main pic + 4 on vertical on the side, I was able to create the look on an outdated carousel but it breaks other things in the page + doesnt show images or post with pictures uploaded by url from outside my blog. Any help or guide in the right direcction will be much appreciated please!! I explain more with examples on my blog http://www.sofiaworld.com/uncategorized/override-default-wordpress-gallery/ Thanks for your time :D
Hi Sofia – well, here’s a few quick suggestions we can make:
1. You can redefine default gallery template by declaring filter ‘post_gallery’
add_filter( 'post_gallery', array( &$this, 'post_gallery' ) );2. You even can totally redefine your gallery shortcode:
add_shortcode( 'gallery', array( &$this, 'gallery_shortcode' ) );3. For reference, what are wordpress outputs for gallery by default, please look up for ‘gallery_shortcode’ function in
wordpress/wp-includes/media.php4. You can attach to ‘gallery_style’ hook that can be found in gallery_shortcode function.
add_filter( '‘gallery_style’', array( &$this, '‘gallery_style’' ) );Hope this helps! Feel free to let us know if you have more questions.