
Using the WordPress gallery shortcode and linking the gallery items to its media source, WordPress will always create a link to the full size image. For a project I needed to change this behaviour since the full size images uploaded by editors will usually be too large to be dealt with the way we want to.
We will be using galleries linking to large size images and displaying them in a fancybox. Unfortunately, the original image sizes are usually very large, like 5.7k pixels wide or even larger. It was taking ages to load the images in the fancybox. So I wanted to make the gallery shortcode link to a smaller version of the image.
By default, WordPress comes with three different default image sizes, that you could set up even without coding through the Settings -> Media panel. As a developer you already will know, how to add custom image sizes, if there’s a need for.
After digging around the internet, I found a solution on how to make the gallery shortcode link to one of the set up image sizes by default, instead of always using the full size image.
Example code to make WordPress gallery shortcode link to custom image size
In your functions.php
place:
1 2 3 4 5 6 7 8 9 10 11 12 | function my_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', 'my_get_attachment_link_filter', 10, 4); |
In the wp_get_attachment_image_src
function, you’d use the size that should be linked to by default – in the code exmaple above it is set to large
. WordPress will have the image sizes thumbnail
, medium
, large
and full
by default plus the ones you set up using the add_image_size
function.
Tuomas says:
Thanks a lot! This post saved a lot of time from me. I was googling a solution for this exact same problem.
Chris says:
Thanks! very helpful, works also for elementor gallery.
Mauricio Araujo says:
Thank you very much!!!
robst says:
Thanks, you’re welcome.
Aaron Wilson says:
This function still works like a champ!!! Thanks.