Improve page speed by automatically adding lazy loading to images in post content.
Steps
- Open your WordPress theme
functions.phpfile. - Add the code below at the end of the file.
- Save the file.
- Clear your cache and test a blog post.
Done — images will load only when they are about to enter the viewport.
function add_lazy_loading_to_images($content) {
return str_replace('<img', '<img loading="lazy"', $content);
}
add_filter('the_content', 'add_lazy_loading_to_images');