wordpress snippets last updated   : July 14, 2014
we now have 634 snippets

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

wordpress snippet

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.

snippet :  PHPcopy
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;
}

  • 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!

    • http://wpsnipp.com Kevin Chard

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

  • Josh

    Worked beautifully! Thanks!

    • http://wpsnipp.com Kevin Chard

      Cool glad to hear you like the snippet.

  • 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 :D

  • http://www.facebook.com/raviraj.deora Raviraj Deora

    Thanks. Perfect.

  • http://twitter.com/offroadbg OFF-road BG

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

  • http://www.phirebase.com/ David Klhufek

    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?

jqsnipp.com | we just launched jquery snippets website