How to automatically add rel=”lightbox” to all images embedded in a post

Paste the following code snippet in your functions.php file. Once done, a rel=”lightbox” attribute will be automatically added to all images embedded in a post.

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;
}

Thanks to Tyler Longren for the snippet!

Leave a Reply

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