How to use prettyPhoto in WordPress Galleries

Just a quick hack I thought I would document to help anyone else out there wondering how to do this.

WordPress now has a simple gallery shortcode, to enable the inclusion of a gallery of all images associated with your post. By default, you just get a grid of images that either link to another page containing the image, or a link directly to the image. Either way, it’s not terribly pretty, and it seems tantalisingly close to something that would look half decent if only something like prettyPhoto (a lightbox clone) could be leveraged. It can!

The gallery shortcode goes something like this:

[gallery link="file"]

It is fully documented here. Basically, this uses the function wp_get_attachment_link inside the /wp-includes/post-template.php file. You could either hack the core function (line 970 on WP3.0) changing:

return apply_filters( 'wp_get_attachment_link', "<a href='$url' title='$post_title'>$link_text</a>", $id, $size, $permalink, $icon, $text );


return apply_filters( 'wp_get_attachment_link', "<a href='$url' title='$post_title' rel='prettyPhoto[slides]'>$link_text</a>", $id, $size, $permalink, $icon, $text );

A better solution

After a bit of reading (thanks to ThemeShaper), I figured out how to use the hooks system, to build a simple function, and filter to modify the output of wp_get_attachment_link. Just pop this code into your template’s functions.php file:

add_filter( 'wp_get_attachment_link', 'sant_prettyadd');
function sant_prettyadd ($content) {
	$content = preg_replace("/<a/","<a rel=\"prettyPhoto[slides]\"",$content,1);
	return $content;

Obviously, you could alter the regex above to do just about anything you like to the output of wp_get_attachment_link, but this does what I set out to do.

PrettyPhoto installation

Obviously, this requires prettyPhoto to be installed and activated on the page for the effect to work. prettyPhoto is available as a WP Plugin – much easier than hacking it into your theme manually. Here’s a sample of how it works:

Tags: ,

30 Responses to “How to use prettyPhoto in WordPress Galleries”