Created
July 25, 2024 18:53
-
-
Save gr1zix/903b58380f1a3340b7260732899786b2 to your computer and use it in GitHub Desktop.
Lazyload images for content in WordPress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_filter('the_content', 'add_loading_attribute_to_content_images_for_lazyload'); | |
function add_loading_attribute_to_content_images_for_lazyload($content) { | |
// Find all images in the content | |
preg_match_all('/<img[^>]+>/i', $content, $images); | |
if (!empty($images[0])) { | |
foreach ($images[0] as $index => $image) { | |
// Check if image already has loading attribute | |
if (str_contains($image, 'loading=')) { | |
continue; | |
} | |
// Receive src attr | |
preg_match('/src="([^"]+)"/i', $image, $src); | |
// check if it first image | |
if ($index == 0) { | |
// If first image gif, then apply loading lazy, otherwise eager | |
if (isset($src[1]) && pathinfo($src[1], PATHINFO_EXTENSION) === 'gif') { | |
$new_image = str_replace('<img', '<img loading="lazy"', $image); | |
} else { | |
$new_image = str_replace('<img', '<img loading="eager"', $image); | |
} | |
} else { | |
// For all other images add loading="lazy" | |
$new_image = str_replace('<img', '<img loading="lazy"', $image); | |
} | |
// Replace image with modified context | |
$content = str_replace($image, $new_image, $content); | |
} | |
} | |
return $content; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment