add rel=”lightbox” to al images in post content (works for cpt as well)

Hi, last day I came into an issue,
I had to transfer a website with lots of content and the site owner wanted me to add a lightbox to open on each image click.
I found some plugins but neither of them worked well.

eventually, I found this guys post,
After reading in I implemented the code to functions.php file.
As well I installed  responsive lightbox plugin.

I saw the code that was there but my code was different, I didn’t have links wrapping my images so this is what I came out with:

function add_lightbox_rel($content) {
    global $post;
    $pattern ="/<img(.*?)src=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\")(.*?)alt=('|\")(.*?)('|\")(.*?)>/i";
    $replacement = '<a$1href=$2$3.$4$5 rel="lightbox" title=$7$8$9 ><img src=$2$3.$4$5 alt=$7$8$9 /></a>';
    $content = preg_replace($pattern, $replacement, $content);
    return $content;
add_filter('the_content', 'add_lightbox_rel');

We use preg_replace to find a pattern and replace it with other structure, What I am doing here is simple. I find all the images in the post and replace them with an a tag wrapping an image.

I turn this:

<img src="./imageurl.png" alt="alternate name">

To this

<a href="/imageurl.png" rel="lightbox">
    <img src="./imageurl.png" alt="alternate name" />

That’s all 🙂

Leave a Comment

Your email address will not be published. Required fields are marked *