The simplest way to modify image links in WordPress WYSIWYG editors!

https://www.powderkegwebdesign.com/simplest-way-modify-image-links-wordpress-wysiwyg-editors/

JANUARY 03, 2017

The default way for WordPress to insert images is to insert them with a link to the full size version. This usually reloads the page with a direct link to the image – something that isn’t what most people expect / go for when they add an image.

There are 2 ways around this:

  1. You can hook in to the “the_content” filter and do some magic:

function my_addlightboxrel($content) {
   global $post;
   $pattern ="/<a(.*?)href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>/i";
   $replacement = '<a$1href=$2$3.$4$5 data-lity title="'.$post->post_title.'"$6>';
   $content = preg_replace($pattern, $replacement, $content);
   return $content;
}

This filter searches for any links that lead directly to an image and modifies their markup. In this particular case, I’m adding the “data-lity” attribute so that they open up in a nice lightbox instead of reloading the page ( Lity is an awesome little lightbox plugin with quite a bit of functionality ). You could also use this filter to add a custom piece of javascript onclick or do some more complex logic to determine if the link is internal vs external and modify it accordingly.

SHARE THIS ARTICLE:

Last updated