Post Format

Creating Photo Gallery Overviews in WordPress

26 comments

One of the cool things recently introduced in WordPress (version 2.5 if memory serves me correctly) is built-in photo galleries. I’d wanted to host my own photo galleries locally for ages instead of relying on a 3rd party like Flickr and once again WordPress came up with the goods in the nick of time (I was getting close to rolling my own which wouldn’t have been ideal).

You may have noticed that when I upload a photo album here on John’s Adventures you don’t see all the photos on the home or archive page, you see a single photo from the album, a description and a link to view the full album. Pretty much like this:

A Photo Gallery Overview

While WordPress doesn’t currently support this functionality out of the box, it’s actually pretty straightforward to implement in your own theme by following these steps…

Add Some Theme Functions

You’ll probably have a file in your theme directory called functions.php – if not then create one (making sure the first line is ‘<?php’ and the last line is ‘?>’ without the quotes) and add the following code to it:

function jc_get_gallery_info( $post_id = 0 )
{
   $post = get_post($post_id);
   $images = get_children( array(
      'post_parent' => $post->ID,
      'post_status' => 'inherit',
      'post_type' => 'attachment',
      'post_mime_type' => 'image',
       'order' => 'ASC',
      'orderby' => 'menu_order ID') );

   if( is_array( $images ) ) {
      $attachments = array_values( $images );
   }
   if( !isset($attachments) || count($attachments) == 0 ) {
      return array( 0, '', 0 );
   }

   $img = wp_get_attachment_image($attachments[0]->ID, 'thumbnail', false);

   $total_comments = $post->comment_count;
   foreach ( $attachments as $k => $attachment ) {
      $total_comments += $attachment->comment_count;
   }

   return array( count($attachments), $img, $total_comments );
}

function jc_comments_number(
   $number, $zero = false, $one = false, $more = false )
{
   if ( $number > 1 )
   {
      $output = str_replace('%', $number,
         ( false === $more ) ? __('% Comments') : $more);
   }
   elseif ( $number == 0 )
      $output = ( false === $zero ) ? __('No Comments') : $zero;
   else // must be one
      $output = ( false === $one ) ? __('1 Comment') : $one;

   echo apply_filters('comments_number', $output, $number);
}

Create a Photo Gallery Category

You’ll need to create a category in WordPress that you’ll assign to all your photo albums to and note down the ID it’s been given. If you go to Manage > Categories in the admin section once you’ve created it and hover over the category you’ll see a URL in your status bar that ends with cat_ID=x – it’s the ‘x’ you’re interested in. On my site that number happens to be 25.

Change The Index and Archive Templates

Next you’ll need to edit any template file that you want to show the overview on. Examples are index.php, archive.php, category.php and search.php. In the default WordPress theme if you have a look at index.php you’ll see the following section:

<?php while (have_posts()) : the_post(); ?>

 <div class="post" id="post-<?php the_ID(); ?>">
	<h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
	<small><?php the_time('F jS, Y') ?> <!-- by <?php the_author() ?> --></small>

	<div class="entry">
	   <?php the_content('Read the rest of this entry &raquo;'); ?>
	</div>

	<p class="postmetadata"><?php the_tags('Tags: ', ', ', '<br />'); ?> Posted in <?php the_category(', ') ?> | <?php edit_post_link('Edit', '', ' | '); ?>  <?php comments_popup_link('No Comments »', '1 Comment »', '% Comments »'); ?></p>
 </div>

<?php endwhile; ?>

Your own theme may look a bit different within the ‘while’ loop but you don’t need to change that, you just need to add the sections between the ‘begin new’ and ‘end new’ comment tags so you end up with the following:

<?php while (have_posts()) : the_post(); ?>

 <!-- begin new -->
 <?php if( in_category(25) && !is_single() ) : ?>

 <div class="photogallery-entry" id="entry-<?php the_ID(); ?>">
   <h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to
    <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
   <small><?php the_time('F jS, Y') ?> <!-- by <?php the_author() ?> --></small>
   <?php $info = jc_get_gallery_info(); ?>
   <div class="entry-content">
     <div class="photogallery-pic"><a title="<?php the_title() ?>"
      href="<?php the_permalink() ?>"><?php echo $info[1]; ?></a></div>
     <?php the_content(' '); ?>
     <p>This album contains <strong><?php echo $info[0]; ?></strong> photos
     <?php jc_comments_number($info[2], '', ' and <strong>1</strong> comment',
      ' and <strong>%</strong> comments' ); ?>.</p>
     <div class="photogallery-view"><a title="<?php the_title() ?>"
      href="<?php the_permalink() ?>">View the whole album &raquo;</a></div>
     <div class="photogallery-footer"></div>
   </div>
 </div>

 <?php else : ?>
 <!-- end new -->

 <div class="post" id="post-<?php the_ID(); ?>">
	<h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
	<small><?php the_time('F jS, Y') ?> <!-- by <?php the_author() ?> --></small>

	<div class="entry">
	   <?php the_content('Read the rest of this entry &raquo;'); ?>
	</div>

	<p class="postmetadata"><?php the_tags('Tags: ', ', ', '<br />'); ?> Posted in <?php the_category(', ') ?> | <?php edit_post_link('Edit', '', ' | '); ?>  <?php comments_popup_link('No Comments »', '1 Comment »', '% Comments »'); ?></p>
 </div>

 <!-- begin new -->
 <?php endif; ?>
 <!-- end new -->

<?php endwhile; ?>

You’ll probably want to tweak the CSS classes that I’m using in the snippet above for your own tastes. Also, note where ’25’ is entered, you’ll want to change that to your photo album category ID.

Update Your Stylesheet

Finally, you need to update style.css in your themes directory to add the classes used above. The ones I’m using here are as follows (just paste the styles below into the bottom of your stylesheet):

.photogallery-pic {
  float: left;
}

.photogallery-pic img {
  display: block;
  position: relative;
  background-color: #fff;
  border: 1px solid #ccc;
  margin-right: 10px;
  padding: 5px;
}

.photogallery-view, .photogallery-view a {
  color: #0066b9;
  font-size: 14px;
  font-weight: bold;
}

.photogallery-footer {
  clear: both;
}

Use The ‘More’ Tag

Now, whenever you create a photo gallery, make sure you put the ‘More’ tag below the text you’d like to appear as the gallery description like so:

Using the 'More' tag

Finished

Now that you’ve made those changes you should see your photo galleries showing up differently on your index and archive pages. Here’s what it looks like applied to the default WordPress theme:

A Photo Gallery Overview in the Default WordPress Theme

And that’s all there is too it! I’m sure there are more efficient ways to achieve this effect and most of it could probably be included in a plugin, but I thought it would make sense if I posted an explanation of how I do it here as a baseline. One final thing to mention is that this works on WordPress 2.6 and above. Hopefully this will be of use to somebody!

Posted by

Creator of John's Background Switcher. Scotsman, footballer, photographer, dog owner, risk taker, heart breaker, nice guy. Some of those are lies.

26 Comments Join the Conversation

  1. John,

    Thank you so much for posting this! This is fantastic!!

    I did run into one problem. The function pulled in my gallery anyway. So I ended up having the gallery photo, then the blurb, then all the photos in the gallery and then the number of photos and comments and the link to view the album.

    Any ideas!

    Thanks again.

    Reply

  2. I may have figured it out. Do you use the MORE quicktag right after your blurb?

    Reply

  3. Well, I’ve tried is out and I get this warning:
    Warning: array_values() [function.array-values]: The argument should be an array in /is/htdocs/wp1029535_9X3YJCZZHB/www/Neuber_Web_Solutions/wordPress/wp2/wp-content/themes/wphotostudio/functions.php on line 10
    I’m really a newbe when it comes to php so John could you help me out please?

    Reply

  4. Ah yes, since it’s the code I use on this site I assume that I’ve got some pictures loaded into the article – I should probably add some more useful error handling to the sample. Very sloppy of me, sorry about that!

    Reply

  5. How about if we used WP tags “if function exist” ..
    erghh..
    Let me try,..

    By the way,.. thanks for this great trick 🙂

    Reply

  6. Hey John,
    I do get that same error on line 10 even tho I do have some posts loaded for the article.

    In idea why this might be happening?

    Reply

    • Are you sure that the gallery in the post in question actually has some pictures loaded into it? It’s actually a warning rather than an error (so I’ll have to change the code snippet to be more graceful) but I reckon your post doesn’t have any pictures loaded into the gallery at this point.

      Reply

  7. Right, I’ve updated the jc_get_gallery_info() function above so you won’t get the warning mentioned. Instead you’ll just not see any pictures in your post (since the warning was triggered by there being no images in the gallery for the post).

    Reply

  8. Hi, is it possible to increase the size of the photo shown, and also those shown when the gallery is opened?

    Did you decide whether or not to make this into a plug in? I’m just scared to play with the code 🙂 But I’ll try if that is still forthcoming….

    Reply

    • The photo sizes are set in the ‘Media Settings’ section of WordPress so you can choose them there!

      Unfortunately it doesn’t really lend itself to being a plugin since you have to edit your theme either way, so your best bet is to modify your theme as I’ve described above.

      Reply

  9. hi- I am trying to go through each step but not seeing the url in this instruction “If you go to Manage > Categories in the admin section once you’ve created it and hover over the category you’ll see a URL in your status bar that ends with cat_ID=x – it’s the ‘x’ you’re interested in. On my site that number happens to be 25.”

    any thoughts?

    I dont have manage categories option- I have a categories section under posts (where I created it) and a link categories section (guessing this is NOT it)

    thanks!

    Reply

    • for what it’s worth- I also don’t have a category.php option to edit….could it be called something different in my theme? (Wasteland)

      Reply

    • one more question- I can upload photos to my media file- how do I upload for these galleries?

      Reply

    • final comment for now- inserted a gallery (figured out the last question) but it is not coming up as pictured above…coming up as all the thumbnails….(have it in draft form right now)

      Reply

    • Ok, first of all, look for ‘Posts’ > ‘Categories’ in WordPress 2.7 and above, the option was moved.

      So long as you’ve followed the instructions (you don’t have to edit category.php if it’s not there, the default template will come into play if the category page isn’t there) you should be good to go.

      Now when you look at the page itself it won’t look any different, you’ll still see the thumbnails as before – have a look at one of my photo pages and you’ll see they’re exactly as they would be on a standard site (pretty much). Where things are different is on the index pages (like your home page, archives, etc), instead of showing the full article it’ll just show the first photo and the summary before the ‘more’ tag – so you won’t actually see if it’s worked or not until you publish your article. If you have a copy of your WordPress site somewhere else that would make testing and debugging it easier.

      Anyway, let me know how you get on and if you still can’t get it to work drop me an email and I’ll be happy to help you out.

      Reply

  10. I am a total word press newbie but not a programming novice. I get the programming you have done – thanks

    I am having trouble understanding how to create a gallery in word press. Maybe it is terminology? Basic BS I have not figured out yet.

    I get unploading media, or pics into a post. How to do I group them in to separate galleries?

    Thanks,

    ed

    Reply

    • You’d be better heading over to the WordPress forums for basic advice on using WordPress. However once you’ve uploaded photos to a post using the buttons next to ‘Upload/Insert’ on the post page you can add a gallery containing those photos by clicking the ‘Gallery’ tab on the ‘Add an image’ popup, then click ‘Insert Gallery’. Easy. Multiple galleries on a post isn’t supported in WordPress 2.7.x, however I believe WordPress 2.8 does have support.

      Reply

Leave a Reply

Required fields are marked *.

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s