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.
Not working
Work just for wordpress?
Not working:(