apply_filters( ‘wp_img_tag_add_loading_attr’, string|bool $value, string $image, string $context )

Filters the loading attribute value to add to an image. Default lazy.

Description

Returning false or an empty string will not add the attribute.
Returning true will add the default value.

Parameters

$valuestring|bool
The loading attribute value. Returning a falsey value will result in the attribute being omitted for the image.
$imagestring
The HTML img tag to be filtered.
$contextstring
Additional context about how the function was called or where the img tag is.

Source

$fetchpriority_val = preg_match( '/ fetchpriority=["\']([A-Za-z]+)["\']/', $image, $match_fetchpriority ) ? $match_fetchpriority[1] : null;
$decoding_val      = preg_match( '/ decoding=["\']([A-Za-z]+)["\']/', $image, $match_decoding ) ? $match_decoding[1] : null;

/*
 * Get loading optimization attributes to use.
 * This must occur before the conditional check below so that even images

Changelog

VersionDescription
5.5.0Introduced.

User Contributed Notes

  1. Skip to note 2 content

    tl;dr ⨪ this will fix your LCP in pagespeed report for lazy loaded images above the fold

    This filter is very useful for images above the fold that don’t need to be lazy loaded (for example logos, featured images etc) so we can hook this filter to read our images and parse for example some custom class that can set lazy loading attribute ON or OFF per image.

    – by setting custom class `skip-lazy` inside admin under `Advanced > Additional Classes` inside image settings:

    add_filter( 'wp_img_tag_add_loading_attr', function( $value, $image ){
    	if ( false !== strpos( $image, 'skip-lazy' ) ){
    		return false;
    	}
    	return true;
    }, 10, 2 );

    disables it

You must log in before being able to contribute a note or feedback.