How To Add A Lightbox To A WordPress Gallery
August 01, 2011
I wanted to setup a simple lightbox photo gallery on a WordPress site (v3.2.1) and, to avoid installing a slew of plugins, I put together a little gallery shortcode function using the built-in WordPress gallery shortcode as my starting point. I’m a big fan of PrettyPhoto, so I modified the output of the gallery shortcode to include the needed rel= attribute for PrettyPhoto galleries.
I grabbed the standard WordPress gallery shortcode from line ~758 in wp-includes/media.php and pasted it into my_theme/functions.php for modification. For the more adventurous folks you can override the default WordPress gallery shortcode and then galleries you’ve inserted using the Media Gallery will be lightboxed.
Here’s the code I ended up with in functions.php (shortened for readability, you’ll need to C&P the entire shortcode function from wp-includes/media.php):
add_shortcode('my_gallery_shortcode', 'my_gallery_shortcode_function'); function my_gallery_shortcode_function($attr) { global $post, $wp_locale; ... foreach ( $attachments as $id => $attachment ) { $link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_link($id, $size, false, false) : wp_get_attachment_link($id, $size, true, false); //add rel="prettyPhoto[pp_gal]" $link = str_replace('><img','rel="prettyPhoto[pp_gal]" ><img',$link); $output .= "<{$itemtag} class='gallery-item'>"; $output .= " <{$icontag} class='gallery-icon'> $link </{$icontag}>"; if ( $captiontag && trim($attachment->post_excerpt) ) { $output .= " <{$captiontag} class='wp-caption-text gallery-caption'> " . wptexturize($attachment->post_excerpt) . " </{$captiontag}>"; } $output .= "</{$itemtag}>"; if ( $columns > 0 && ++$i % $columns == 0 ) $output .= '<br style="clear: both" />'; } $output .= " <br style='clear: both;' /> </div>\n"; return $output; } |
My edit was small, I added $link=str_replace('><img','rel="prettyPhoto[pp_gal]" ><img',$link); to the gallery output so that PrettyPhoto can do it’s thing.
Now that you have that all you need to do is be sure you’re including the necessary files:
<link rel="stylesheet" type="text/css" media="all" href="<?=bloginfo('template_directory');?>/prettyPhoto/css/prettyPhoto.css" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script> <script type="text/javascript" src="<?=bloginfo('template_directory');?>/prettyPhoto/js/jquery.prettyPhoto.js"></script> |
And be sure to call PrettyPhoto:
<script type="text/javascript" charset="utf-8"> $(document).ready(function(){ $("a[rel^='prettyPhoto']").prettyPhoto(); }); </script> |
Now all you need to do is upload photos to your gallery and use this shortcode on your page:
[my_gallery_shortcode link="file"] |
And that’s it! A quick solution to adding a lightbox to your WordPress gallery.