How to automatically add rel=”lightbox” to all images (WordPress)

Send Us a Sign! (Contact Us!)
Word PDF Epub Text
XML OpenOffice XPS MHT

The well known jQuery plugin Lightbox is a very simple way to open images in fancy full-screen boxes. It is very easy to use, but you have to add a rel=”lightbox” attribute to each image you want to open in a lightbox. Here’s a cool code snippet to automatically add the rel=”lightbox” attribute to all images embedded in your posts.


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;