// Automatically add loading="lazy" to all img tags that lack a loading attribute
add_filter('the_content', 'add_lazy_loading_to_content_images', 99);
function add_lazy_loading_to_content_images($content) {
if (is_admin()) {
return $content;
}
return preg_replace_callback('/
]+)>/i', function($matches) {
$img = $matches[0];
// Skip if loading attribute is already defined or if fetchpriority="high" is set
if (strpos($img, 'loading=') !== false || strpos($img, 'fetchpriority="high"') !== false) {
return $img;
}
// Inject loading="lazy"
return str_replace('![]()