Automatically Add rel=”lightbox” To All Embedded Images In A Post

Although using the Lightbox plugin can be a nice way of giving your readers a great experience in viewing your images in your blog, it can also become a bit tedious adding the rel=”lightbox” attribute to each image that you want to open with it. But thanks to Tyler Longren‘s code snippet, you won’t have to anymore.

Rellightbox Automatically Add rel=”lightbox” To All Embedded Images In A Post

Copy/paste the code below in to your functions.php file. Once done, every image you embed in a post will automatically have a rel=”lighbox” attribute added to it.

add_filter('the_content', 'my_addlightboxrel');
function my_addlightboxrel($content) {
global $post;
$pattern ="/<a(.*?)href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>/i";
$replacement = '<a$1href=$2$3.$4$5 rel="lightbox" title="'.$post->post_title.'"$6>';
$content = preg_replace($pattern, $replacement, $content);
return $content;
 }

And by the way, in line 5 of the code you can change the rel=”lightbox” to whatever you prefer as Tyler noted that some viewer scripts use rel=”thumbnail” among other things. This snippet also adds the post title as the title attribute of the image’s anchor tag.

Incoming search terms for the article:

Related Posts

How to Create an Appealing Coming Soon Page

How to Create Text with Flaming Meteor Effect

Creating Shiny Retro Text

Creating a Psychedelic Art Effect in Your Portraits