Tech Notes: Using Resized Images in WordPress Galleries and Lightboxes

In my opinion, WordPress isn’t great at handling media. Well, it’s better than some other CMS’ I’ve used, but it’s still not amazing. This post describes a little WordPress functions.php tweak that makes takes a bit of hassle out of using WordPress galleries with a lightbox plugin.

Background

The background to this is that I have a client who has lots of photos on his website, displayed in WordPress galleries, using a simple jQuery lightbox plugin to show the photos in a nice way.

To make the Lightbox work, the gallery needs to use links to the image files rather than to the attachment pages.  It’s simplest form looks something like:

[gallery link="file"]

However, linking directly to the file is a problem if you’re uploading large image files, as the lightbox displays the full-size image. This is annoying because, if you upload a large image, the lightbox takes ages to download the picture. It’s also unnecessary, as WordPress cleverly creates thumbnail, medium and large versions of your images when you add them to the media library.

What would be really handy would be if the gallery could link to one of the resized versions of the image, thus keeping the load times down for the lightbox images without the end-user having to worry about resizing images.

UPDATE: lyndonr has commented that the original code here deleted title attributes from the links. He’s right and I’ve updated the code as a result. Apologies to anyone that this affected.

This little code snippet does exactly that. Add it to your functions.php and it will use the ‘large’ version of the image wherever WordPress is displaying a link to an attached image.

function oikos_get_attachment_link_filter( $content, $post_id, $size, $permalink ) {

	// Only do this if we're getting the file URL
	if (! $permalink) {
		// This returns an array of (url, width, height)
		$image = wp_get_attachment_image_src( $post_id, 'large' );
		$new_content = preg_replace('/href=\'(.*?)\'/', 'href=\'' . $image[0] . '\'', $content );
		return $new_content;
	} else {
		return $content;
	}
}

add_filter('wp_get_attachment_link', 'oikos_get_attachment_link_filter', 10, 4);

Technical Details

The walk through the code that I used to get to this was:

gallery_shortcode() (in media.php) does:

$link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_link($id, $size, false, false) : wp_get_attachment_link($id, $size, true, false);

to get the link-wrapped img (e.g. <a href="...."><img ... /></a>)

wp_get_attachment_link() is in post-template.php and, for link=file does

$url = wp_get_attachment_url($_post->ID)

wp_get_attachment_url() is in post.php

When we’re linking to file we want wp_get_attachment_url() to return the ‘large’ image, rather than the full-size image.

I initially set a filter on the wp_get_attachment_url hook, and the filter used wp_get_attachment_image_src( post_id, 'large' ) to get the URL of the large image size. HOWEVER, this resulted in a loop because wp_get_attachment_image_src() (which is in media.php) calls image_downsize() (also in media.php), which then uses wp_get_attachment_url() to get the URL. Which calls our filter…and so on.

So I had to look back up the chain of calls a bit and do something higher up. I settled on filtering on wp_get_attachment_link and using the regular-expression to replace the href attribute. The regular expression is probably not bomb proof, but it gets the job done.

Hope that’s helpful to someone!

Tags: , , , , , , , ,

  • http://www.mbstrategic.com Ted B

    This is fantastic! I was searching around and found a link to this tutorial from the wordpress threat below. I dropped your script into my functions.php file and it worked perfectly. Thanks for posting this.

    http://wordpress.org/support/topic/how-to-make-link-to-large-image-instead-of-full-size?replies=23

    • Oikos Administrator

      Hi Ted. Thanks for letting me know about the WordPress.org thread. Glad the code was helpful!

  • Foomarks

    This works awesome! I would also love to see a method where you can pass a variable in the shortcode so that you can pick and choose an image link size on a post-to-post basis. Like this:

    Post 1: [gallery link="large"]

    Post 2: [gallery link="medium"]

    Post 3: [gallery link="custom_1000px"]

  • Tim

    I added this to my functions.php but I didnt notice any changes.

    Not sure what I could have done wrong.
    Just pasted the snippet at the end of the functions.php file in the theme right?

    We still have big lightbox images: http://www.synergine.co.nz/synergine-presents-environmental-engineering-award/

    Any ideas?

    T

    • Anonymous

      Hi Tim,

      Sorry this isn’t working for you. It’s hard to know without seeing your exact WordPress configuration, but I think you might have a lightbox plugin that’s interfering with my code – perhaps it is also filtering the links?

      I’ve had another look through my code and the only thing that I can see that might not always work is the type of quotes I’m using in the link.

      Could you try changing line 7 of my code to:

      $new_content = preg_replace(‘/href=”(.*)”/’, ‘href=”‘ . $image[0] . ‘”‘, $content );

      Thanks – let me know how you get on.

    • RossWintle

      Hi Tim,

      I was looking through these comments again as there’s some new ones and checked your site out again. Not sure if you’re using some other code now but it looks like this is working for you. On the page you’ve linked to, when you click the image it opens a lightbox with a 1024×768 px image (http://www.synergine.co.nz/wp-content/uploads/2011/11/EnvEng702-1024×768.jpg). This is, I think, the “large” version of the file that WordPress has scaled down from the original. The original is http://www.synergine.co.nz/wp-content/uploads/2011/11/EnvEng702.jpg.

      I wonder if we’re using different definitions of “large”. You may be saying that the image is visually too big, but actually, your lightbox plugin resizes an image to fit the brower window. The code I’ve written is more intended to load a smaller file size (EnvEng702-1024×768.jpg is 162kb, whereas the original EnvEng702.jpg is nearly 2MB).

      Hope that helps.

    • oikos_uk

      Hi Tim,

      I was looking through these comments again as there’s some new ones and checked your site out again. Not sure if you’re using some other code now but it looks like this is working for you. On the page you’ve linked to, when you click the image it opens a lightbox with a 1024×768 px image (http://www.synergine.co.nz/wp-content/uploads/2011/11/EnvEng702-1024×768.jpg) This is, I think, the “large” version of the file that WordPress has scaled down from the original. The original is http://www.synergine.co.nz/wp-content/uploads/2011/11/EnvEng702.jpg

      I wonder if we’re using different definitions of “large”. You may be saying that the image is visually too big, but actually, your lightbox plugin resizes an image to fit the brower window. The code I’ve written is more intended to load a smaller file size (EnvEng702-1024×768.jpg is 162kb, whereas the original EnvEng702.jpg is nearly 2MB).

      Hope that helps.

  • Evi

    Thanks a lot. Exactly that what I have searched for.
    Its a stupid worpress setting that the full images are displayed.

  • .:: [F]usion[S]tream ::. — on

    The API appears to have changed in 3.3.1… If you could confirm that you could perhaps write an update code for this. If you don’t I’ll try my hand at it…

    • RossWintle

      Hi there – sorry for not replying sooner. Not had a chance to test this on 3.3 or 3.3.1 yet. I’ll take a look if I get the time. Thanks for the comment and subsequent links to other useful/similar code.

    • oikos_uk

      Hi there – sorry for not replying sooner. Not had a chance to test this on 3.3 or 3.3.1 yet. I’ll take a look if I get the time. Thanks for the comment and subsequent links to other useful/similar code.

  • .:: [F]usion[S]tream ::. — on

    Function does not appear to be called. Confirming that it’s the theme’s function?!

  • .:: [F]usion[S]tream ::. — on

    Solution found for those looking for the single image version of this.
    http://posterous.jefflundberg.com/make-wordpress-image-link-to-large-image-inst

    Thanks to authors of both posts!

  • http://restaurantconnectinc.com/ Ted Bradley

    This is fantastic! Just what I’ve been looking for. Thanks.

    • oikos_uk

      Hi Ted, glad it’s been helpful and thanks for the comment.

  • damirkotoric

    Incredible! You’ve just saved me hours my friend. Thank you.

    • oikos_uk

      Glad it worked for you – glad the post was helpful!

  • AG

    THANK YOU SOOOOOO MUCH !

  • Pingback: Setting up a successful WordPress blog - image configuration

  • http://twitter.com/DaveJamesMiller Dave James Miller

    Brilliant, thank you!

  • lyndonr

    this works great except it seems to strip out the title attribute. any idea how to preserve this? I added back in the width and height to your regular-expression replace, but the metadata comes from elsewhere.

    • lyndonr
      • http://oikos.org.uk/ Ross Wintle

        Hi Lyndon,

        Thanks for posting this and sorry I didn’t get around to looking at it for you. I double-checked the code and couldn’t see why anything was interfering with the titles, and I just didn’t have time to conduct some tests and do some debugging.

        From your updated snippet it looks like the regular expression is gobbling up the title attribute as well as the href attribute. Another fix should to just modify the preg_replace line to read:

        $new_content = preg_replace(‘/href=’(.*?)’/’, ‘href=” . $image[0] . ”’, $content );

        (If you missed it, I just added a ? into the regular expression pattern to make it “lazy”)

        In theory this is a more robust change because the regular expression would include, and therefore replace, everything between the first single-quote and the last single-quote in the link. So if your link included a class, or id, after the href, that used single-quotes, that would disappear too.

        Again, I’ve not tested this, but you’re welcome to give it a go and let me know how it goes.

        Thanks for raising it and for finding a fix too. I’ll update the post.

  • sandrine

    Fantastic, you saved my life !!! Thanks for sharing

  • Mr Random

    Thanks, this helped a lot!

  • Bernhard

    Could it be that this only works in articles and not in pages? If yes, how to get this to work in page contents? I deactivated the lightbox plugin but still nothing happens, everytime the original image is linked…

    • http://oikos.org.uk/ Ross Wintle

      No reason why it wouldn’t work on a page that I know of. Have you got a link to the page so I can see what’s being generated?

  • wellsincambodia

    This works great thanks! Now the only problem is people don’t have access to the full-sized images on my site. Is there a way to create a download button link in prettyPhoto so that users could download the full-sized images?

  • Angelo

    I have the same problem. The images in my WordPress gallery are linking to the full size images which are too large. This code snippet fix isn’t working or isn’t compatible with WordPress version 3.4.2.

    • http://oikos.org.uk/ Ross Wintle

      Hi Angelo. I have this code running OK on WP 3.4.2. Can you provide a link so I can see the page that’s not working? Thanks.

  • smartssa

    Very useful. Thanks!

  • Pingback: Wordpress Plugin: Gallery Link Size Changer | Wonderm00n

  • http://www.facebook.com/profile.php?id=614356061 Mark van der Putten

    Awesome solution and really works like a charm, it really helped me out big time! Thanks!

    • http://oikos.org.uk/ Ross Wintle

      Glad the snippet helped Mark, and thanks for the link back to this post

  • Pingback: Linking Wordpress gallery images to thumbnails - Mark van der Putten

  • vince

    Hi, can this be done for single image, i.e NOT in gallery.

    btw, it worked splendidly for gallery in WP 3.5.1 for me :-)

    would love a filter which, when inserting pict into post, would take default for image size too.
    I insert image into post, as thumbnail size, it links to “media file” now… full image.

    dropdown says media file, attachment page, custom url, none.

    Any change of figuring out a way to add “large” to these options via filter?

    • http://www.facebook.com/dimitri.lekien Dimitri Lekien

      Hello vince.
      Did you get an answer to your question ?
      Thanks

  • http://oikos.org.uk/ Ross Wintle

    Hi folks,

    Just want to add to anyone that’s getting emailed updates that I’ve added a teeny-tiny update to the code here that fixes a very embarrassingly simple schoolboy PHP error.

    It is left to the reader to explain what I did wrong.

    I fully blame the ridiculousness of the PHP ‘language’ that lets you make such simple errors. Something that no half-decent language should do!

    Ross

  • Paul Bennion

    Can we confirm if this code works for 3.5.1 as it is breaking my site and returning 500 internal error regardless of which theme i have activated.

    • http://oikos.org.uk/ Ross Wintle

      Hi Paul,

      Sorry it took a while to get back to you – I was very busy and then on holiday.

      I’ve just tested this code in WordPress v3.5.1 and it works just fine.

      Did you resolve your problem or are you still having errors?

      Ross

  • http://oikos.org.uk/ Ross Wintle

    Hi guys,

    Really sorry for not replying sooner. I’ve been dreadfully neglectful of my blog comments.

    I get what you’re trying to do here and I did some searching and found this that works with WP versions prior to the new media manager in v3.5: http://abundantdesigns.com/2012/11/12/link-to-the-large-image-from-wordpress-media-uploader/

    I’ve not found a solution for v3.5. Perhaps the Abundant Designs code could be modified for v3.5+?

    Let me know if you find anything.

    Ross

  • Pingback: Link to different size images from a WordPress media gallery « PixelPress Wiki

  • Bogdan

    Works perfect, many thanks!

  • Pingback: Gallery Shortcode: Using Link Attribute To Link To A Specific Image Size | Click & Find Answer !

  • Pingback: Gallery Shortcode – Change Link File Image Size? (not Using Default Fullsize Image) | Click & Find Answer !

  • Pingback: Add Download Button In PrettyPhoto Plugin | Click & Find Answer !

  • Stefano Pettenuzzo

    Hi, what about wordpress 3.8.1 ?
    it doesn’t work for me
    thanks

    • http://blog.wintle.me.uk/ Ross Wintle

      Hi Stefano,

      Sorry it’s not working for you. I’ve not tested the code recently and I’ve got a REALLY busy week this week. Let’s see if anyone else chips in with a suggestion.

      • Sarah

        Hi Ross, just to let you know that the code is also not working in WordPress 3.9 – it appears to be ignored and continues to open the photos as their full size.

        • http://oikos.org.uk/ Ross Wintle

          Hi Sarah, Stefano,

          Had a quick look into this this morning. Could you post a link to a gallery that’s not working?

          Now there’s a “doing_action” function I’ve a mind to rewrite how this works as it can be made much simpler and more logical.

          Hang in there for how!

          Ross

          • vEGA

            Great, waiting for this. :)

        • http://oikos.org.uk/ Ross Wintle

          Sarah, Stefano,

          I’ve just tested this on an install of 3.9 and it works fine!

          My guess would be that you have another plugin installed that is conflicting with the code that I’ve written.

          Let me see if I can come up with some new code for 3.9.

          Ross

        • http://oikos.org.uk/ Ross Wintle

          Actually, the new functions in WP3.9 don’t help. So the code above is all I have I’m afraid.

          If you can post a link to your gallery that’s not working then I’ll see if I can take a look.

          Ross

        • vEGA

          Well, I have it working with newest WordPress running and no plugins. I will try now the Caroussel plugin (without Jetpack).

          • vEGA

            Okay, the plugin wants the big size, of course, and so it is not working. That had to be changed directly in the plugin code, I guess.

          • vEGA

            But I did get it working with another plugin. So, your code still seems to be valid. :)