Adding a rel attribute to image anchor tags in WP galleries

I’m using Fancybox as a lightbox on this site, which was working fine for individual images. But when I posted the gallery of three images in my previous post, I realised the images weren’t linked together in a gallery in a way Fancybox understood. What’s needed is the rel attribute, and a quick google showed loads of people suggesting the same snippet to add to the functions.php file:

/**
 * Give a rel attribute to all gallery images in a post
 */
function st_add_rel_attribute( $link ) {
    return str_replace( '<a href', '<a rel="st-gallery" href', $link );
}
add_filter( 'wp_get_attachment_link', 'st_add_rel_attribute' );

Looking at the gallery_shortcode() function in Core, there is at least one easy improvement to make that will distinguish between galleries in different posts – useful when posts are being displayed in a list on a page. We just add the post ID to the end of our rel attribute:

/**
 * Give a rel attribute to all gallery images in a post
 */
function st_add_rel_attribute( $link ) {
    global $post;
    return str_replace( '<a href', '<a rel="st-gallery-'.$post->ID.'" href', $link );
}
add_filter( 'wp_get_attachment_link', 'st_add_rel_attribute' );

Better, but still not there – what about two galleries in the same post? I couldn’t see a way of handling that with filters in Core – so the best I could do was a jQuery solution. We add a class to the anchor tag to help the jQuery find the right links, and then add in the jQuery snippet to wherever we’re initialising Fancybox:

/**
 * Give a rel attribute to all gallery images in a post
 */
function st_add_rel_attribute( $link ) {
    global $post;
    return str_replace( '<a href', '<a class="st-gallery-link" rel="st-gallery-'.$post->ID.'" href', $link );
}
add_filter( 'wp_get_attachment_link', 'st_add_rel_attribute' );
//give rel attribute to img anchor tags in WP galleries
$( 'div.gallery' ).each( function() {
    var galleryId = $(this).attr('id');
    if ( undefined !== galleryId ) {
        $( this ).find( 'a.st-gallery-link' ).attr( 'rel', galleryId );
    }
});

And there we have it. Two galleries below – open up an image and you can move to the other image in the same gallery, but you don’t spill over into the other gallery…

Gallery 1

Gallery 2

Leave a Reply

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