Home / functions.php / Add rel=”lightbox” to all images embedded in a post
  • How to 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.

    ( click code to copy )

    wordpress snippet : PHP

    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;

    ( WordPress codex functions, hooks, in this snippet. )

    the_content, add_filter,
  • Pingback: Wordpress : How to add rel=”lightbox” to all images embedded in a post « Wordpress « Cms « Codes php – Share your php snippets()

  • Angela

    Thank you for this!

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

  • Josh

    Worked beautifully! Thanks!

  • Hafizur

    Thank you for this!

  • WPSpeak

    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 😀

  • Thanks. Perfect.

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

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

  • Buzz

    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?

  • ???????! ????????!