Try Tuts+ Premium, Get Cash Back!
The WordPress Gallery Shortcode: A Comprehensive Overview
basix

The WordPress Gallery Shortcode: A Comprehensive Overview

Tutorial Details
  • Program: WordPress
  • Version: 3.0+
  • Difficulty: Easy
  • Estimated Completion Time: ~ 30 minutes

If you haven’t had the chance to use the WordPress Gallery Shortcode in the past, this is going to be a great starting out point for you. For others who have used it, we are going to be covering some features of the shortcode that you might not have considered yet. In this tutorial we will be covering a specific WordPress shortcode, and the different ways to use it.


Introduction

WordPress has little code snippets, called shortcodes, that can be used in Posts, Pages, and Post Types. WordPress has many shortcodes, which can be added to using the shortcode API, covered here. These shortcodes, placed in the content editor area or placed in a theme file, are connected to functions that run when the content or post is loaded. WordPress shortcodes are flexible, often allowing you to specify options that customize the way the shortcode works.

Today we’ll be going over the shortcode specifically, but you can also read up on our other intro posts to shortcode usage in WordPress:


Basic Usage

To get started with the shortcode go to Posts section and add a New Post which we will call “Gallery Post”. In the editor area place the shortcode (in either the Visual/HTML View). After that press Publish/Update.

The page will be refreshed and if you tab to the Visual editor you will now see a dashed box with a photo icon in the middle. If you click on the box, in the top left corner you will see another picture icon. Click on that icon and a dialog window will popup. This dialog window will allow you to upload and attach images to the post. Go ahead and either drag and drop your pictures into the drop region or press Select Files and choose the photos you want to upload.

After you upload the images you will want to press “Save all changes”. That will bring you to the “Gallery” tab in that same dialog window. You will see thumbnails of all the images you just uploaded as well as some settings. Look around, change some settings to see the different options. Now adjust the Gallery columns to 5 and then press “Update gallery settings”.

Now go ahead and press View Post. You will see the post with a gallery grid of images, with 5 columns. If you click on an image, it will take you to the image attachment post.


Gallery Shortcode Output

Now that we see the shortcode is working, let’s go ahead and check out the source code and see what is being outputted.

<style type='text/css'>
 #gallery-1 {
      margin: auto;
 }
 #gallery-1 .gallery-item {
      float: left;
      margin-top: 10px;
      text-align: center;
      width: 20%;
 }
 #gallery-1 img {
      border: 2px solid #CFCFCF;
 }
 #gallery-1 .gallery-caption {
      margin-left: 0;
  }
</style>
    

What you see above is the first part of the code WordPress automatically generates per shortcode.The CSS is automatically outputted for each shortcode that is used. There are default elements and classes for each gallery and each element wrapping an image. If you had a second gallery on the page it would ouput #gallery-2 ..

Below is the rest of the code, the HTML generated by the gallery. You can see the gallery is wrapped in a div and each image and caption is wrapped in elements as well.

<div id='gallery-1' class='gallery galleryid-1 gallery-columns-5 gallery-size-thumbnail'>
	<dl class='gallery-item'>
			<dt class='gallery-icon'>
				<a href='http://localhost/wp-tuts/2011/12/10/hello-world/wp-tut-1/' title='Pretty Text'><img width="150" height="150" src="http://localhost/wp-tuts/wp-content/uploads/2011/12/wp-tut-1-150x150.jpg" class="attachment-thumbnail" alt="Pretty Text" title="Pretty Text" /></a>
			</dt>
				<dd class='wp-caption-text gallery-caption'>
				Pretty Text
				</dd></dl><dl class='gallery-item'>
			<dt class='gallery-icon'>
				<a href='http://localhost/wp-tuts/2011/12/10/hello-world/wp-tut-2/' title='Berries!'><img width="150" height="150" src="http://localhost/wp-tuts/wp-content/uploads/2011/12/wp-tut-2-150x150.jpg" class="attachment-thumbnail" alt="Berries!" title="Berries!" /></a>
			</dt>
				<dd class='wp-caption-text gallery-caption'>
				Berries!
				</dd></dl><dl class='gallery-item'>
			<dt class='gallery-icon'>
				<a href='http://localhost/wp-tuts/2011/12/10/hello-world/wp-tut-3/' title='Quad in River'><img width="150" height="150" src="http://localhost/wp-tuts/wp-content/uploads/2011/12/wp-tut-3-150x150.jpg" class="attachment-thumbnail" alt="Quad in River" title="Quad in River" /></a>
			</dt>
				<dd class='wp-caption-text gallery-caption'>
				Quad in River
				</dd></dl><dl class='gallery-item'>
			<dt class='gallery-icon'>
				<a href='http://localhost/wp-tuts/2011/12/10/hello-world/wp-tut-4/' title='wp-tut-4'><img width="150" height="150" src="http://localhost/wp-tuts/wp-content/uploads/2011/12/wp-tut-4-150x150.jpg" class="attachment-thumbnail" alt="Store" title="wp-tut-4" /></a>
			</dt>
				<dd class='wp-caption-text gallery-caption'>
				Store
				</dd>
		</dl>
			<br style='clear: both;' />
		</div>

Shortcode Options

Now that we got a taste of the basic usage of the gallery shortcode, let’s check out all the different options for customizing the output. The shortcode options include columns, id, size, link, include, exclude, orderby, order, itemtag, icontag, and captiontag.

columns

If you go back to the HTML tab in the post editor you will see the shortcode says . When we adjusted the column settings in the gallery interface, it passed those settings into the shortcode. Now instead of using the graphic interface, let’s manually specify the settings through the shortcode. Let’s change the colums=”5” to colums=”2”. Now go View Post – you can see that there is a grid of the gallery pictures, and instead of 5 images per column, there is 2. Let’s view the source again on the “Gallery Post” and see what WordPress outputs. Right before the gallery in the source we can see the CSS – notice the difference from the previous CSS output? This CSS is automatically generated by the shortcode. If you change the columns you will notice how the CSS changes.

#gallery-1 .gallery-item {
	float: left;
	margin-top: 10px;
	text-align: center;
	width: 50%;
}

The CSS essentially adjusts the width to 100 / $columns, $columns being either 3 by default or a number we specify in the shortcode .

id

By default, the gallery shortcode pulls the gallery associated with the current post id. However if you specify ID, you can pull images from another post. To test this lets add a new post and call it Other Page. Go ahead and upload some different pictures to Other page and press Publish. Then up in the browser URL address, look for post=.

Remember that number and then go back to Gallery Shortcode post and then add the gallery shortcode (use the number id from the other post in place of 99). Update the Gallery Shortcode post and then go View Post. Notice how there are now two galleries, one with images from the “Gallery Shortcode” post and the other images are from the “Other Page”. You can also adjust the options on the shortcode, changing columns, order etc.

size

The default size for the gallery images is thumbnail. Other options include “thumbnail”, “medium”, “large” and “full”. “thumbnail”, “medium”, “large sizes are specified under WordPress Settings > Media. Full size is simply the full size of the image. If we change the settign to size=”large” then WordPress will output the image and crop/scale it to the associated dimensions. The default “large” size for WordPress is Max Width 1024 & Max Height 1024 , so images will be scaled and cropped to fit that size. (side note, images can be custom cropped in WordPress the way you want.)

*Side note, your images will be skewed if they are much larger than the specified size.

orderby

By default, the images are ordered by ‘menu_order’ (which I highly recommend you leave) other options include ‘ID’ ,’title’ – order by title. ,’date’ – order by date image was uploaded, ‘modified’ – order by last date image was updated or changed & ‘RAND’ – order items randomly.

order

After you set the ‘orderby’ you can set ‘ASC’ or ‘DESC’ (don’t use if ‘orderby’ is not set or set is set to ‘menu_order’). So for example, if you want the images to be listed alphabetically backwards (Z-A) by image title you make sure orderby=”title” and then also specify order=”DESC” (default is ASC).

link

By default the gallery images each link to the attachment page of each image. So in other words, each image goes to essentially a single post, with the image. If you want to link to the source of the image (my-image-name.jpg) you can pass in .

include

Sometimes you may want to include only very specific images. You can do that by using the include option, (23,39,45 are an example, use ID’s that match up with your images) You pass in the ID of each image you want associated. To find the ID’s of the images go to Media > Library and then click on each of the images you want.

In the browser URL bar look for wp-admin/media.php?attachment_id= and then write down and use that number in the gallery shortcode following the format shown above.

exclude

This option is pretty much exactly what it sounds. If you follow the instructions for include, find the ID’s of the images you DON’T want in the gallery. After you find the images you don’t want included (only look for images you don’t want that are attached to the post) . Please note, if you use include and exclude the internet will break! Okay not really, but it won’t work! It will ignore the exclude and use only the include.

itemtag, icontag , captiontag

These options can actually change the HTML elements that WordPress outputs with the gallery shortcode. The default option tags are as follows: itemtag=”"dl”, icontag=”dt”, captiontag=”dd”. In essence the default gallery shortcode for these options is . Say we wanted to change the HTML tags, we could easily pass in the element we would prefer used, so we could use something like . Try those options out and you can see the difference in output.

<div id='gallery-1' class='gallery galleryid-1 gallery-columns-2 gallery-size-thumbnail'><section class='gallery-item'>
		<div class='gallery-icon'>
			<a href='http://localhost/wp-tuts/2011/12/10/hello-world/wp-tut-1/' title='Pretty Text'><img width="150" height="150" src="http://localhost/wp-tuts/wp-content/uploads/2011/12/wp-tut-1-150x150.jpg" class="attachment-thumbnail" alt="Pretty Text" title="Pretty Text" /></a>

		</div>
			<figure class='wp-caption-text gallery-caption'>
			Pretty Text
			</figure></section><section class='gallery-item'>
		<div class='gallery-icon'>
			<a href='http://localhost/wp-tuts/2011/12/10/hello-world/wp-tut-2/' title='Berries!'><img width="150" height="150" src="http://localhost/wp-tuts/wp-content/uploads/2011/12/wp-tut-2-150x150.jpg" class="attachment-thumbnail" alt="Berries!" title="Berries!" /></a>
		</div>
			<figure class='wp-caption-text gallery-caption'>
			Berries!
			</figure></section><br style="clear: both" /><section class='gallery-item'>

		<div class='gallery-icon'>
			<a href='http://localhost/wp-tuts/2011/12/10/hello-world/wp-tut-3/' title='Quad in River'><img width="150" height="150" src="http://localhost/wp-tuts/wp-content/uploads/2011/12/wp-tut-3-150x150.jpg" class="attachment-thumbnail" alt="Quad in River" title="Quad in River" /></a>
		</div>
			<figure class='wp-caption-text gallery-caption'>
			Quad in River
			</figure></section><section class='gallery-item'>
		<div class='gallery-icon'>
			<a href='http://localhost/wp-tuts/2011/12/10/hello-world/wp-tut-4/' title='wp-tut-4'><img width="150" height="150" src="http://localhost/wp-tuts/wp-content/uploads/2011/12/wp-tut-4-150x150.jpg" class="attachment-thumbnail" alt="Store" title="wp-tut-4" /></a>
		</div>

			<figure class='wp-caption-text gallery-caption'>
			Store
			</figure></section><br style="clear: both" />
		<br style='clear: both;' />
	</div>

Theming the Gallery

If you are creating or customizing a theme there are some primary classes you want to look out for. These are classes that the gallery outputs in the HTML, every time a shortcode is used.

Gallery Wrap

The “Gallery Wrap” wraps every instance of the shortcode. That means if you use the shortcode three times, this wrap will exist in the source code three times. Each time the is used in a post, the output id is incremented.

<div class="gallery galleryid-1 gallery-columns-3 gallery-size-large" id="gallery-1"><div>

  • .gallery – wraps every gallery included in a post
  • .galleryid-{$id} – increments, if second then the {$id} would be 2
  • .gallery-columns-{$columns} – changes depending on column option
  • .gallery-columns-{$size} – changes depending size option

Other Elements

  • .gallery-item – wraps each gallery image and caption
  • .gallery-icon – inside of .gallery-item, wraps anchor to image (file or link) and image
  • .gallery-caption – inside of .gallery-item, wraps image caption text

Enhancing Our Gallery CSS

So now that we understand the basics of the shortcode, the different options and it’s available CSS/classes let’s check out how we can enhance the CSS that is already there. (For this section and the next, we are assuming you understand the basics of CSS.) In the TwentyEleven theme, the default gallery looks like the gallery from the screenshots in the previous sections.

WordPress already outputs the basic CSS for the layout, but we can add some more styling to give the gallery extra pizzaz. In the theme that we are working with (for TwentyEleven /wp-content/themes/twentyeleven/style.css or other themes /wp-content/themes/*themename/style.css) open the style.css in an editor add this code to the end of the stylesheet.

.gallery .gallery-item{
	position:relative;
}

.gallery .gallery-caption{
	position:absolute;
	bottom:4px;
	text-align:center;
	width:100%;
}

.gallery .gallery-icon img{
	border-radius:2px;
	background:#eee;
	box-shadow:0px 0px 3px #333;
	padding:5px 5px 40px 5px;
	border:solid 1px #000;
}

Knowing the classes of the element we are able to target the specific parts of the gallery. With this styling we are able to target each of the images and give them a Polaroid’ish look


Overriding Gallery CSS

In some cases you may want to override the existing CSS for the shortcode. Since we know the elements and the CSS the outputs, if we wanted to, we could easily override the CSS – we could do this by using CSS specificity. Since there is only one layer of specificity and the only id being specified is #gallery-1 (1 for the first gallery, and numbering continues for each gallery in post) you could override the CSS simply by finding a parent id (for TwentyEleven #content works) and then also specify .gallery, since it’s a class attached to each gallery.

#content .gallery {
	/* This style would override the default #gallery-1 styling */
	margin:0px;
	display:none;
}

Obviously above is a basic example of overriding the CSS, but you get the gist!


Conclusion

The builtin shortcode for WordPress is pretty handy with all sorts of options to set up a custom gallery. It’s not perfect, as we saw in a screen earlier, but it works very well. Stay tuned, and in the upcoming weeks learn how to retool the gallery shortcode with lightbox and slider options!

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://toyskiddy.co.cc Kiddy

    It’s Cool,Any Question How We can get the shortcode from any themes ? can u see me about hierarchy ?

  • http://www.kreativtheme.com Kreativ Theme

    Thanks for the great gallery tutorial … some code bits will go on my wordpress theme

  • http://socialmedia101.artizondigital.com Sue Surdam

    Great tutorial! Is there a way to use photos you already have in your media library in a gallery?

    • http://www.laceytechsolutions.co.uk Ben Lacey

      If you go to the page for your gallery and click on the media upload button you will see an option for Media Library. Click on that, find the image you want and click Insert into post. Then update the page.

      This will cause WordPress to “Attach” the inserted image to the page, allowing it to be included in the Gallery.

    • http://ahermosilla.com Andres Hermosilla
      Author

      @Sue you can pass in the id of each image you want to include using the *include* option – it’s a bit cumbersome, but without any plugins that’s the only way to do it.

      • http://socialmedia101.artizondigital.com Sue Surdam

        Thanks for your great answers, Ben and Andre. I will explore them both.

    • http://unrelatedmedia.ca Neil Davidson

      Don’t forget another, often overlooked, method. Sometimes you don’t want to simply insert images into your post but you want to connect an image with a post. Well, you can attach an image to a post by reference by simply…

      1)Click on Media
      2)Click on the attach link of the image you wish to attach
      3) type in the page or post you want to attach the image to
      4) Accept.

      So far as I’ve ever used this for you can only assign a single image to be attached to a post or page. I could be, and actually hope I am, wrong on this.

      The advantage of this is that you can assign 1,000, 10,000 or more images to a post and when you load that page in the browser it doesn’t slow down at all to load all those images – which happens when you insert images into a post.

      Because the images are directly related by reference to the post you can create a custom code to pre-load them if you need to in your functions or template file. Alternately you can simply load images as they need to be visible. Lastly, you could have 10 images attached by reference to a post/page and call only a specific image(s) at a time. Maybe for use with a random image display each time the page is loaded.

      Just remember – this method doesn’t load the images when a post or page is loaded but simply assigns the image to that post or page. None of the attached images, with this approach, get loaded unless you tell them to.

  • Pingback: Best WordPress Resources Websites Part2 | Tarak Brahmi

  • http://joefreymahusay.com Joefrey Mahusay

    Thanks for sharing this tutorial. Very useful indeed! :)

  • Pingback: WordPress Gallery Shortcode » VC-TEL Team Blog

  • Gurpreet

    Is it possible to do the following?
    I would like to upload more than a 2000 pictures to my gallery. Each of these pictures or thumbnail has a unique name/number/tag and its description, that i would like my viewers to see..
    I would prefer that my viewer searches a picture by its name/number, and then click on it to enlarge and see the description.
    Alternatively, Each thumbnail can have a name/number as a caption below it, as well as its description beside it; only clicking it takes it to the enlarged view.
    The picture name/number or tag has to be searchable.

    • http://unrelatedmedia.ca Neil Davidson

      Yep. All media types have metadata. WordPress lets you access this meta data with wp_get_attachment_metadata()

  • http://www.sanjaykhemlani.com sanjay

    Cool! I didn’t know about the postID and orderby, thanks a lot!

  • http://s2webpress.com Steven

    I would like to see a more in depth tutorial about changing the output. This is essential for creating themes with custom galleries while maintaining the use of the [gallery] shortcode.

  • http://datcang.info Nguyen

    Thank you. This tutorial is very useful

  • http://academicwriterjobs.com ahmadshorif

    Nice tutorial for only absolute beginner (i think).Very easy language used in this tutorial.

  • Pingback: Tweet-Parade (no.2 Jan 2012) | gonzoblog.nl

  • http://- Jay

    Very nice run down! thanks.

    I’m trying to create a news article with i have a gallery at the top.
    and below i have the text write-up, with a few thumbnails to break up the text.

    The problem is, the thumbnails are being pulled into the gallery.! the exclude ID dosent seem to work ether. strange..

    Any help would be so much appreciated.

  • Pingback: Tweet Heat - The hottest Tweets of the Month [January 2012] | Inspired Magazine

  • http://shipwreckedwithyou.com Chloe Johnston

    Is there any way to lay out a gallery so that every fifth image is larger than the rest? Or do you always have to pick a standard size and stick with it?

    • http://unrelatedmedia.ca Neil Davidson

      Funny – I just wrote a tutorial on this concept. Use the PHP Modulus with WordPress

      Also, the bonus code at the bottom can be used to display a gallery of images from a post right inside the template file.

      Now, I don’t know why the author made it so complicated. Really, you can add an action hook to run this:

      <?php
      $args = array(
      ‘numberposts’ => -1, //the amount of images to retrieve
      ‘post_type’ => ‘attachment’, //defined post type
      ‘status’ => ‘publish’, //the status of the post (draft, published, etc)
      ‘post_mime_type’ => ‘image’, //e.g. image, video, video/mp4
      ‘post_parent’ => $post->ID, //the ID of the post we want to use
      ‘order’=> ‘ASC’,
      ‘orderby’ => ‘title’
      );
      $images = &get_children($args); //post is the parent, and attachments are children of parent. Get the children
      //loop through the post attachments

      ?>

      Then place that in a function that returns all the images as an array or object. You can look at the rest of the code there which just uses the modulus as with the rest of the tutorial for layout but the concept of displaying is easily done.

      The point is, using PHP Modulus gives more control in layout of the gallery and would be a far better approach then what the author is suggesting. Simply add a variable to a function call that defines the amount of images you want per row and include that in teh template or shortcode wherever.

      The Modulus tutorial can be used to do what you are asking as well. Say you set the modulus column to 3 and load a “large” image instead of the thumbnail for every third image.

  • Lee

    It is a good tutorial for beginner.Do you use the theme “twentyeleven” in this tutorial?

    • http://ahermosilla.com Andres Hermosilla
      Author

      Yup!

  • http://www.sthlmwebdesign.com Michael

    Is there any way to change the default settings for the gallery? I desperately need to make it default to linked images rather than posts. I’m dealing with a blog network and have tons of users that can’t all be expected to modify the settings themselves.

    • thirddoor

      You could add this snippet to your functions file:

      update_option(‘image_default_link_type’,'file’);

  • http://www.sofiaworld.com sofia

    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

  • Michael S.

    Hi, is it possible to get the clicked image show on the same page as the gallery? Instead of opening up a new post/page?

  • jm

    “Stay tuned, and in the upcoming weeks learn how to retool the gallery shortcode with lightbox and slider options!”

    When do we get the followup tutorial?

  • http://www.ravenousravendesign.com Heather

    I’ve noticed that when using the Gallery shortcode it will automatically pull in images from somewhere else that are not even on the page/post. Has anyone else had this problem?

    I’m using Genesis.

    • http://www.mindyourskills.com Johnathen

      i have never experienced this problem i am also using genisis.

  • http://gpsmna.org Anne Marie Doherty

    I added about 20 pics to a gallery and about three out of twenty of them link back to the thumbnail size when I click on them. I have looked at link and it appears to be going to original photos. When I view them in cpanel or media library they are correct size. Would appreciate any help on this.

    Also, why does wordpress make four copies of each photo with different sizes? If I delete the two extras is that a problem? Thanks.

    • http://ahermosilla.com Andres Hermosilla
      Author

      WordPress automatically generates different image sizes depending on your media settings. These different sizes are available when your insert images into posts. It shouldn’t really affect anything deleting the “extra images” but I personally wouldn’t.

  • http://www.eventdecorstudio.com Bensky

    is there a way to use short code to have it display the title of the image?

    on my site the gallery displays perfectly like i want it to except i want the thumbnails to display the title of the image as well. i have over 700 photos and it would take forever to manually add a caption to each one. is there a shortcode trick to having it display the title as well?

    thank you

    • Andres Hermosilla
      Author

      You could rewrite the gallery shortcode – copy and paste the existing one but change the output to where the title is outputted instead of the caption.

  • Steve

    I have created my own gallery shortcode using add_shortcode and everything works great except the “edit gallery” visual editor is lost (this> http://wptutsplus.s3.amazonaws.com/158_GalleryShortcode/wp-tuts-gallery-shortcode-an2dres5m@gmail/images/screen-gallery-icon.png)

    Does anyone know where in WordPress this exists?

    • http://ahermosilla.com Andres Hermosilla
      Author

      Your account may have the visual editor disabled. Poke around in your profile settings, otherwise your theme or a plugin may have disabled it.

  • http://twitter.com/vronini vroni

    Hi, thanks for your explanation. I need a way to not give a certain amount of columns for a responsive theme. The solution should put each image beside each other regarding the viewport. If the end of a row is reached the next image should float left to the next row. And NOT presenting them in a masonry wall. Can I somehow disable the fix column amount?
    Any help would be great! Thanks in advance.

  • http://www.facebook.com/michele.massari Michele Massari

    is there a way to use the gallery shortcode and force it to use all the images in the media library?

  • A Man Cooks

    Wow. The bit with the ID made my day. Thanks boss.