Make your WordPress gallery link to a custom image size


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:

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.

Like this post? Share it!

5 thoughts on “Make your WordPress gallery link to a custom image size

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>