Change image src to data-src for lazy load using image_send_to_editor filter

For a recent project I needed to use lazy load for images inserted within posts. So I come up with the following solution. This snippet uses image_send_to_editor and will filter the HTML output replacing src with data-src then adding a new src attribute with a default image thumbnail. This is a pretty simple solution but allows me to control the output created within the post editor to ensure images that clients add are lazy loaded. You will 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 are 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.

Code Snippet:

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!