Add Lightbox To All Images Embedded in a WordPress Post

Make every image in a post open in a lightbox

I needed to do this about a year ago, attach rel="lightbox" to every image inside a WordPress post, so that the image would open in a lightbox. The lightbox plugin we were using wasn’t adding rel=”lightbox” to some images for whatever reason, so this was my quick alternative. Turned out to be incredibly simple with WordPress’s add_filter() function.

add_filter() allows developers to hook a function up to a specific filter action. There’s TONS of action and filter hooks available, some are really, really useful. A great introduction to filter and actions hooks can be found at WPCandy or in the WordPress Codex. Smashing WordPress has a quite detailed article, too.

Anyway, as usual, when adding this type of thing to WordPress, drop this code in your theme’s functions.php file to get this working:

function add_lightbox_rel($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;
add_filter('the_content', 'add_lightbox_rel');

You should be aware that some plugins don’t use rel="lightbox" for activating their lightbox/colorbox overlay. So, if that’s the case, just modify the theme_add_lightbox_rel() function and change rel="lightbox" to rel="whatever-plugin-uses" in the $replacement variable (on line 5).

That’s it! Save your functions.php file and you should have lightboxes on all the images embedded in your post!

Plugin Alternative

If you’d prefer to achieve this with a plugin, I’d suggest jQuery Colorbox. It does a really nice job of grouping gallery images, used for the next and previous links for navigating the gallery images.


Well, now what?

Work with Me

I'm available for hire and always taking new clients, big and small. Got a project or an idea you'd like to discuss? Startup plan but no developer to make it happen? Just get in touch, I'd love to see if I can help you out!

Leave some Feedback

Got a question or some updated information releavant to this post? Please, leave a comment! The comments are a great way to get help, I read them all and reply to nearly every comment. Let's talk. 😀 is proudly hosted by DigitalOcean


3 thoughts on “Add Lightbox To All Images Embedded in a WordPress Post

  1. fix for escape quotes:

    function add_lightbox_rel($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;
    add_filter(‘the_content’, ‘add_lightbox_rel’);


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.