How To: Style Your WordPress Gallery

How To: Style Your WordPress Gallery

18 septembre 2016 0 Par Nicolas

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 theuse_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.cssand 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'

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 asTwitpic or yfrog and post up the links. If you have any questions or trouble following this tutorial feel free to ask.