Remove Lazy loading on first image in Wordpress

Viewed 2520

i want to remove lazy loading on the first image in Wordpress, for every posts, pages and home.

I don't use any plugins for lazy loading image, i need a solution for the default lazy loading add by wordpress.

I found this script for functions.php, but it is for WP Rocket plugin, and i haven't this plugin.

So i modified it in this:

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(utf8_decode($content));

        $imgs = $document->getElementsByTagName('img');
        $img = $imgs[0];

        if ($imgs[0] == 1) { // Check if the post has images first
            $img->setAttribute('class','aligncenter size-full remove-lazy');
            $html = $document->saveHTML();
            return $html;
        }
        
        else {
            return $content;
        }
     }
     else {
         return $content;
     }
}
add_filter ('the_content', 'add_responsive_class');

Now, i need to remove the lazy load only on image with class "aligncenter size-full remove-lazy".

I try with this, after the above code, but i have an error and it doesn't work:

function remove_lazy_loading_for_specific_class( $attributes ) {
    $attributes[] = 'class="aligncenter size-full remove-lazy"';
    return $attributes;
}
add_filter( 'wp_img_tag_add_loading_attr', 'remove_lazy_loading_for_specific_class' );

How can I do that? Thanks

2 Answers

Not sure if this would be helpful but instead of all of this why not give this image an ID or a class and remove the lazy attribute that WordPress adds by default using the removeAttribute() method.

I solved only with this :)

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(utf8_decode($content));

        $imgs = $document->getElementsByTagName('img');
        $img = $imgs[0];

        if ($imgs[0] == 1) { // Check if the post has images first
            $img->removeAttribute( 'loading' );
            $html = $document->saveHTML();
            return $html;
        }
        
        else {
            return $content;
        }
     }
     else {
         return $content;
     }
}
add_filter ('the_content', 'add_responsive_class');
Related