Add Unique Rel Attribute to Each Gallery Within a Post

Rel attributes are used by many gallery/slideshow scripts (thickbox, fancybox, colorbox) for grouping images into galleries. In my previous articles I explained how to add unique rel attributes to all images within one post using a simple WordPress filter.

WordPress 3.5 enabled us to add multiple galleries per one post and it would be great if we could group them into separate batches as well. Unfortunately, it can’t be done (easily) using PHP so we need to rely on javascript for this one.

Here is a simple snippet of jQuery that finds all separate galleries on the page and adds a unique rel attribute per gallery:

jQuery('.gallery').each(function(g) {
    $('a', this).attr('rel', function(i, attr) {
        return attr + ' gallery-' + g;
    });
});

Note how it leaves the existing rel attributes untouched and only appends a unique gallery identifier. Here is a working example of the script on jsfiddle.

Leave a Reply