Are you looking for a way to add lightbox attribute to all the images embedded in your posts? While there’s probably a plugin for this, we have created a quick code snippet that you can use to add rel=”lightbox” to all images embedded in a post and also add the post title as the title attribute of the image anchor tag in WordPress.
Instructions:
All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:
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; }
Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.
If you liked this code snippet, please consider checking out our other articles on the site like: How to transfer WordPress from local server to a live site and 7 best WordPress lead generation plugins.
If there’s a custom link or a link to the attachment page this adds the data attributes to the image instead which breaks the link. It also breaks srcset images.
???????! ????????!
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?
well. that’s what makes me happy today.. thanks ))
Hi all! It’s sounds great, but is there any exact place in the function.php where to put the code?
Thanks. Perfect.
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 😀
Thank you for this!
Worked beautifully! Thanks!
Cool glad to hear you like the snippet.
Thank you for this!
No problem glad you like the snippet, be sure to follow wpsnipp or like us for new snippets! Enjoy.
[…] WPsnipp [!] Report this snippet Processing your request, Please wait…. […]