X

How to Change Image SRC to Data-SRC for Lazy Load Using image_send_to_editor Filter

Snippets by IsItWP

Are you looking for a way to change image src to data-src for lazy load using image_send_to_editor filter? While there’s probably a plugin for this, we have created a quick code snippet that you can use to change image src to data-src for lazy load.

Instructions:

All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:

function example_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', 'example_lazy_load', 10, 9 );

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. Make sure you update the $src variable with the URL to your default thumbnail image.

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly add code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: 50+ best WooCommerce themes for your online store and 7 best WordPress GDPR plugins.

Comments   Leave a Reply

  1. Victoria Castello February 1, 2023 at 8:24 pm

    Not working

  2. Dendy Imobiliare March 15, 2019 at 2:09 pm

    Work just for wordpress?

  3. Not working:(

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!