I’ll have a look into this and let you know, when I know what is wrong.
However a comment about this:
Building a DOMDocument
instance with for every HTTP request is quite “expensive” since that means that the whole DOM needs to be parsed to create a DOM tree in memory. Also keep in mind that utf8_decode()
is deprecated in PHP 8.2 (see https://www.php.net/manual/en/function.utf8-decode.php). You may want to use iconv()
or mb_convert_encoding()
instead.
Your code has errors.
First you ask the DOM to get all img
elements:
$imgs = $document->getElementsByTagName('img');
Then you use the first elemement in that collection:
$img = $imgs[0];
And then compare the same element if it is 1
:
if ($imgs[0] == 1) { // Check first if it is the first image
This will not work. $imgs[0]
is not a number, but a DOMElement
instance.
So should rather just check, if there are any images at all and if so, just use $imgs[0]
, because that is already the first image:
function disable_lazy_first_image($content){
if ( is_singular() || is_front_page() || is_home() ) {
$content = mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8");
$document = new DOMDocument();
libxml_use_internal_errors(true);
$document->loadHTML(utf8_decode($content));
$images = $document->getElementsByTagName('img');
// Only work on that if there are any images
if ($images->length > 0) {
$images[0]->removeAttribute( 'loading' );
$html = $document->saveHTML();
return $html;
}
else {
return $content;
}
}
else {
return $content;
}
}
add_filter ('the_content', 'disable_lazy_first_image');
But even this makes no sense, since 'the_content'
will be called for every single post and not for the whole page! So in this case you will remove the lazy loading attribute from all images on the home page and not just for the first image.
Also I don’t see what performance gain you get when disable lazy loading only for the first image. If the image is in the view port it will be loaded anyway, even if lazy loading is enabled.
In addition: learn how to use XDebug and how to setup a local test environment for WordPress – this will show you much more than just “trial & error”.