Categories
Development

Incorporating Lightbox 2 effect with WordPress gallery

I wanted my client to be able to add pictures to a gallery using the build in WordPress gallery, but was hoping to customize the display of the gallery thumbs a bit. I was hoping to get it to display as the following:

      use the Lightbox 2 script
      able to override the CSS that is being written to the page

Since the default CSS that the gallery generates is written in the page, overriding the styles was kinda a pain to do in the site’s stylesheet I was using. However I did find that I could edit the default CSS that is being written to the page by the gallery by editing the following file:

/wp-includes/media.php

Locate the following code and edit as necessary:

	$output = apply_filters('gallery_style', "
		<style type='text/css'>
			#{$selector} {
 
			}
			#{$selector} .gallery-item {
				float: left;
 
				text-align: center;
							}
			#{$selector} img {
 
			}
			#{$selector} .gallery-caption {
				margin-left: 0;
			}
		</style>
		<!-- see gallery_shortcode() in wp-includes/media.php -->
		<div id='$selector' class='gallery galleryid-{$id}'>");

You can see I’ve removed some styles in this case.

Further edits can be made to the gallery from this file as well. I chose to use a little bit of javascript to attach the rel attribute to my anchors instead of editing the php file. Personally, I’d rather do that so in case a future version of WordPress altered the media.php file it’d be one less thing for me to worry about.

Very basic javascript to add the rel attribute that Lightbox 2 requires to the image anchors:

var galleryDivs = YAHOO.util.Dom.getElementsByClassName('gallery', 'div', 'bd');
for (var i = 0; i < galleryDivs.length; i++) {
    var imageAnchor = galleryDivs[i].getElementsByTagName('a');
    for (j = 0; j < imageAnchor.length; j++) {
        imageAnchor[j].setAttribute('rel', 'lightbox[gallery]');
    }
}

I use the YUI Dom collection to help me gather nodes.

Then it’s just a matter of calling the relevant dependancy scripts and styles into your page and it should work for you.

3 replies on “Incorporating Lightbox 2 effect with WordPress gallery”

Leave a Reply

Your email address will not be published. Required fields are marked *