To add lazy load on images in content the loading="lazy"
attribute to images in WordPress programmatically, you can use a filter function. Here’s an example of how you can achieve this:
Add lazy load on images in content
function add_responsive_class($content) {
if (is_single() || is_page() || is_front_page() || is_home()) {
$content = mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8");
$document = new DOMDocument();
libxml_use_internal_errors(true);
$document->loadHTML('<?xml encoding="UTF-8">' . $content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); // This helps to load the content without adding extra doctype, html, and body tags.
$imgs = $document->getElementsByTagName('img');
$first = true;
foreach ($imgs as $img) {
if ($first) {
$img->setAttribute('loading', 'eager'); // Set loading="eager" for the first image
$first = false;
} else {
$img->setAttribute('loading', 'lazy'); // Set loading="lazy" for all subsequent images
}
$img->removeAttribute('decoding'); // Remove decoding="async" from all images
}
$html = $document->saveHTML();
return $html;
} else {
return $content;
}
}
add_filter('the_content', 'add_responsive_class', 99); // Using priority 99 to ensure it runs after other content filters
This code will find all images which coming into the_content hook. and it will add loading=”lazy” for all images. Also you can add and remove another attribute in content using setAttribute & removeAttribute.
“We’ve implemented lazy loading for images on our website to improve performance and user experience. Lazy loading delays the loading of images that are not immediately visible on the screen, loading them only when they are about to come into view. This reduces the initial page load time, as the browser doesn’t need to load all images at once, especially beneficial for pages with lots of images or long-scrolling content. This optimization technique helps in faster page rendering, lower data usage, and a smoother browsing experience for our visitors.”
“By implementing lazy loading, we aim to provide a more efficient and enjoyable browsing experience for our visitors, especially those on slower internet connections or mobile devices. This optimization aligns with our commitment to delivering fast, accessible, and user-friendly content. We believe that these enhancements will not only improve the overall performance of our website but also enhance the overall user satisfaction.”
You can add this code to your theme’s functions.php
file. This function will add the loading="lazy"
attribute to all images in the content of single posts, pages, the front page, and the home page.
- 8 Essential Checks Before Submitting Your Website Design Project to Clients
- How to create custom post type in wordpress
- How to set default country in woocommerce using hook
- 301 Redirection by .htaccess
- How to redirect page on another page using html meta or javascript