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: , , , , , , , ,

67 Responses to “Tech Notes: Using Resized Images in WordPress Galleries and Lightboxes”

  1. Ted B October 18, 2011 at 12:42 am #

    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 October 19, 2011 at 9:09 am #

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

  2. Foomarks November 9, 2011 at 8:22 pm #

    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"]

    • hw June 3, 2014 at 3:23 pm #

      me too! why this is not standard added in WP? it’s so simple o ad.

  3. Tim November 16, 2011 at 5:29 am #

    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 November 16, 2011 at 8:49 am #

      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 January 19, 2012 at 10:32 am #

      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 January 19, 2012 at 10:48 am #

      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.

  4. Evi November 23, 2011 at 12:25 pm #

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

  5. .:: [F]usion[S]tream ::. -- on January 6, 2012 at 3:36 pm #

    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 January 19, 2012 at 10:19 am #

      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 January 19, 2012 at 10:47 am #

      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.

  6. .:: [F]usion[S]tream ::. -- on January 6, 2012 at 3:48 pm #

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

  7. .:: [F]usion[S]tream ::. -- on January 7, 2012 at 12:46 pm #

    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!

  8. Ted Bradley January 27, 2012 at 5:37 pm #

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

    • oikos_uk January 27, 2012 at 7:10 pm #

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

  9. damirkotoric March 6, 2012 at 9:36 am #

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

    • oikos_uk March 7, 2012 at 5:12 pm #

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

  10. AG June 4, 2012 at 3:22 pm #

    THANK YOU SOOOOOO MUCH !

  11. Dave James Miller June 24, 2012 at 11:13 am #

    Brilliant, thank you!

  12. lyndonr July 16, 2012 at 4:27 pm #

    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 July 19, 2012 at 9:31 pm #

      here’s a solution for missing title…

      http://wordpress.org/support/topic/help-get-image-link-title-in-this-function

      • Ross Wintle July 20, 2012 at 10:01 am #

        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.

  13. sandrine July 17, 2012 at 12:17 pm #

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

  14. Mr Random July 21, 2012 at 12:15 pm #

    Thanks, this helped a lot!

  15. Bernhard August 28, 2012 at 1:00 am #

    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…

    • Ross Wintle August 28, 2012 at 9:32 am #

      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?

  16. wellsincambodia October 12, 2012 at 10:49 am #

    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?

  17. Angelo October 23, 2012 at 6:17 am #

    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.

    • Ross Wintle October 23, 2012 at 10:52 am #

      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.

  18. smartssa November 6, 2012 at 9:30 pm #

    Very useful. Thanks!

  19. Mark van der Putten December 14, 2012 at 9:31 pm #

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

    • Ross Wintle December 17, 2012 at 10:11 am #

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

  20. vince February 15, 2013 at 3:26 am #

    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?

    • Dimitri Lekien April 15, 2013 at 2:09 pm #

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

  21. Ross Wintle March 16, 2013 at 8:59 pm #

    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

  22. Paul Bennion April 20, 2013 at 9:20 am #

    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.

    • Ross Wintle May 7, 2013 at 10:44 am #

      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

  23. Ross Wintle May 7, 2013 at 11:00 am #

    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

  24. Bogdan July 12, 2013 at 9:55 am #

    Works perfect, many thanks!

  25. Stefano Pettenuzzo March 3, 2014 at 9:53 am #

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

    • Ross Wintle March 3, 2014 at 10:05 am #

      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 April 17, 2014 at 2:38 am #

        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.

        • Ross Wintle April 17, 2014 at 9:56 am #

          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 April 18, 2014 at 1:12 pm #

            Great, waiting for this. :)

        • Ross Wintle April 18, 2014 at 3:32 pm #

          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

        • Ross Wintle April 18, 2014 at 3:45 pm #

          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 April 18, 2014 at 8:39 pm #

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

          • vEGA April 18, 2014 at 9:59 pm #

            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 April 19, 2014 at 10:18 am #

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

  26. lambusdean77 May 12, 2014 at 2:07 am #

    dude, THANK YOU SO MUCH. i wasted so much time trying to figure out how to display large images.

  27. Chad May 29, 2014 at 9:53 pm #

    I get the following with a 3.9 install:

    Fatal error: Call to undefined function add_filter() in /home/strike9/public_html/eatsleeptinker.com/wp-includes/functions.php on line 4467

    • Ross Wintle June 9, 2014 at 12:54 pm #

      Ah, you need to put this in your theme’s functions.php, not in wp-includes/functions.php

      It’s really bad practice to modify WordPress core code. You shouldn’t be editing anything in wp-includes !

      • Chad June 28, 2014 at 8:40 pm #

        Ahh…. So I tried that as well, still having links to the media file open the fullsize image. Does this work on any links to the media file or only when using the gallery? I primarily have thumbnail or smaller images on my posts, with links to the media file, which is then opened in a lightbox. Thanks!

        • Chad June 28, 2014 at 8:51 pm #

          So I tried out a gallery, which worked. Here’s a test post showing what I describe. The fullsize image is 5520 x 3680 and 9.11MB.

        • Ross Wintle June 28, 2014 at 9:06 pm #

          It won’t work on individual images, only galleries, or other places where an attachment link is automatically generated by WordPress.

          Unfortunately the “Insert media” button in the WordPress editor only lets you link to the “Media file”. It doesn’t let you choose a specific size to link to.

          Having different sizes of media file listed in the “Link to” box is something that was suggested in another comment thread below. I’ve not built a way to do this; perhaps someone else has?

          A workaround is to just use a single-image gallery.

          Hope that helps.

          Ross

          • Chad June 28, 2014 at 9:10 pm #

            Ross,

            That’s unfortunate that WP is designed this way. Using a single image gallery isn’t very ideal for normal “magazine” style posts where the image thumbnails may be dispersed throughout the text with varying sizes and locations. I’ll keep looking.

            Thanks again,
            Chad

          • Ross Wintle June 28, 2014 at 9:14 pm #

            Hi Chad,

            It is sad. Other options are:
            – just find out the URL of the resized image you want to link to and link to that
            – don’t link to anything. An image in an article shouldn’t necessarily link through to a larger image. In fact, I don’t think any of the major news outlets do this.

          • Chad June 29, 2014 at 10:17 pm #

            Ross,

            Yes I have tried it by using a custom link directly to the medium or large file URL. That is very tedious and not practical at all (especially given the amount of posts already published.)

            Not linking is fine for some posts, but the majority of them would not be an option. There isn’t enough detail presented on a small thumbnail.

            I know this isn’t your problem, just venting. I am surprised that there is no plugin to resolve this (or better yet make it integral to WP.) There are multiple threads regarding this, none with a solution at WP.

            -Chad

Trackbacks/Pingbacks

  1. Setting up a successful WordPress blog - image configuration - June 6, 2012

    […] plugin instead – but if I did then I would’ve applied the solution explained here: Using Resized Images in WordPress Galleries and Lightboxes […]

  2. Wordpress Plugin: Gallery Link Size Changer | Wonderm00n - November 23, 2012

    […] Based on the oikos.org.uk solution. […]

  3. Linking Wordpress gallery images to thumbnails - Mark van der Putten - December 14, 2012

    […] I was having a huge problem for one of my clients where I had to link the standard WordPress gallery images not too their full original versions but to a re-sized smaller version so that they would always fit the page when loading into a lightbox. After a while of searching on Google I found this great article by Ross from Oikos: http://oikos.org.uk/2011/09/tech-notes-using-resized-images-in-wordpress-galleries-and-lightboxes/ […]

  4. Link to different size images from a WordPress media gallery « PixelPress Wiki - May 12, 2013

    […] Taken from here: http://oikos.org.uk/2011/09/tech-notes-using-resized-images-in-wordpress-galleries-and-lightboxes/ […]

  5. Gallery Shortcode: Using Link Attribute To Link To A Specific Image Size | Click & Find Answer ! - December 20, 2013

    […] http://oikos.org.uk/2011/09/tech-notes-using-resized-images-in-wordpress-galleries-and-lightboxes/ […]

  6. Gallery Shortcode – Change Link File Image Size? (not Using Default Fullsize Image) | Click & Find Answer ! - December 23, 2013

    […] Code from http://oikos.org.uk/2011/09/tech-notes-using-resized-images-in-wordpress-galleries-and-lightboxes/ […]

  7. Add Download Button In PrettyPhoto Plugin | Click & Find Answer ! - December 24, 2013

    […] I use the prettyPhoto Media plugin on my site, and I have also used this code (taken from this post) in order to allow prettyPhoto to view a smaller image than the full sized image in galleries so […]

Leave a Reply