Filter WordPress Gallery Image Link

Dec 31, 2012

I'm lazy, and I know a few lazy people who follow the same lazy process as I do when creating galleries in WordPress:

The problem with this, is the process does not account for batch resizing of images. Especially for sites like mine that "link" to "file" for a lightbox affect, this means we are serving the ~3MB photo when a gallery thumbnail is clicked (I actually feel this is a shortcoming with WordPress, and users should be able to "link" to any image size).

By default, WordPress does a great job resizing images; It gives us three sizes: thumbnail, medium, and large - you can change these sizes via your WordPress admin by navigation to Settings -> Media. So why not leverage this? The following code will hook into the call to function wp_get_attachment_link and set the returned link to be the 'large' image size. The side effect is, whenever this function is called (not just within the context of a gallery) with the $permalink parameter set to false, it will always return the 'large' image size. However, that is not a problem for me.

The code below can be added anywhere to your theme - most commonly, it will be your themes' functions.php file.

/**
* Filter the gallery thumbnail links to link to the 'large'
* image size and not the 'full' image size.
*
* @param $html
* @param $id
* @param $size
* @param $permalink
* @return string
*/
add_filter( 'wp_get_attachment_link', function( $html, $id, $size, $permalink ) {
	if ( false !== $permalink )
		return $html;
	list( $link, , ) = wp_get_attachment_image_src( $id, 'large' );
	return preg_replace( "/href='([^']+)'/", "href='$link'", $html );
}, 1, 4 );