Change Image src to data-src for Lazy Load Using image_send_to_editor Filter

Are you using lazy loading for images inserted in your posts? You probably should be. Lazy Loading allows your website to only load images when a reader scrolls down to that specific image. This keeps your site running at peak speed performance.

This snippet uses image_send_to_editor and will filter the HTML output replacing src with data-src then adds a new src attribute with a default image thumbnail. This is a pretty simple solution, but it allows you to control the output created within your post editor to ensure images clients add are lazy loaded. You’ll need to make sure you update the $src variable with the URL to your default thumbnail image. Once you update the thumbnail image just add this snippet to the functions.php of your WordPress theme and you’re all set.

If you are looking for a lazy load plugin wpsnipp.com is using Unveil.js a lightweight jQuery plugin for lazy loading images.

function wpsnipp_lazy_load($html, $id, $caption, $title, $align, $url) {
  $src  = 'src="'.get_template_directory_uri().'/i/thumb.png"';
  $html = str_replace( "<img src", "<img {$src} data-src", $html );
  return $html;
add_filter( 'image_send_to_editor', 'wpsnipp_lazy_load', 10, 9 );

Comments  Leave a Reply

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!