Add rel=”lightbox” to all images embedded in a post

Adding this snippet to the functions.php of your wordpress theme will add a rel="lightbox" attribute to all images embedded in your post. Also note that on line 05 you can change the rel="lightbox" to whatever you need as some image viewer scripts will use rel="thumbnail" for example. This snippet will also add the post title as the title attribute of the images anchor tag.

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;

Comments  Leave a Reply

  1. ???????! ????????!

  2. How would i go about changing the title attribute to display the images caption intstead? I’ve tried replacing .$post->post_title. with .$attachment->post_excerpt but doesn’t work. Any idea what I’m doing wrong?

  3. well. that’s what makes me happy today.. thanks ))

  4. Hi all! It’s sounds great, but is there any exact place in the function.php where to put the code?

  5. Thanks. Perfect.

  6. How to use it for video? WordPress autoembed feature is great, but I hate it that if I want to show the video in lightbox, I’ve to add some class etc to the video. It’d great it there’s workaround to autoadd the rel=lightbox to video too 😀

  7. Thank you for this!

  8. Worked beautifully! Thanks!

    1. Cool glad to hear you like the snippet.

  9. Thank you for this!

    1. No problem glad you like the snippet, be sure to follow wpsnipp or like us for new snippets! Enjoy.

  10. Wordpress : How to add rel=”lightbox” to all images embedded in a post « Wordpress « Cms « Codes php – Share your php snippets October 14, 2011 at 5:41 am

    […] WPsnipp [!] Report this snippet Processing your request, Please wait…. […]

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!