Skip Navigation
Madison, Wisconsin
Powderkeg Web Design
January 3, 2017

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

Nick
Nick
The simplest way to modify image links in Wordpress WYSIWYG editors!

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. When you add media to your wysiwyg editor you can select that the link be “none” on the right side column towards the bottom:
  2. You can hook in to the “the_content” filter and do some magic:
    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 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.

Nick Kalscheur

Nick Kalscheur

Lead Developer