This is how images are output in WordPress:
<figure class="no-lazy"><img loading="lazy" class="wp-image-12345" src="apple.jpg" alt="apple"></figure>
I want to adjust the loading attribute for images in WordPress. I am currently using the following solution using str_replace:
add_action( 'template_redirect', function(){
ob_start( function( $buffer ){
$buffer = str_replace( array( '<figure class="no-lazy"><img loading="lazy"', "<figure class='no-lazy'><img loading='lazy'"), '<figure class="no-lazy"><img loading="eager"', $buffer );
return $buffer;
});
});
However, I believe there is a better way to achieve my goal using wp_img_tag_add_loading_attr.
The wp_img_tag_add_loading_attr solution only works if the class is assigned directly to the image element (img) as follows:
<img loading="lazy" class="no-lazy" src="apple.jpg" alt="apple">
Here's the wp_img_tag_add_loading_attr code that changes the loading attribute of images with class="no-lazy" from lazy to eager:
add_filter( 'wp_img_tag_add_loading_attr', 'skip_lazy_load', 10, 3 );
function skip_lazy_load( $value, $image, $context ) {
if ( strpos( $image, 'no-lazy' ) !== false ) $value = 'eager';
return $value;
}
The issue in WordPress is that the class is added to the figure and not the image as follows:
<figure class="no-lazy"><img loading="lazy" src="apple.jpg" alt="apple"></figure>
How do I use preg_match and wp_img_tag_add_loading_attr to achieve the same thing as the str_replace solution above?
'/<figure [^£]*?my_css_class[^£]*?<\/figure>/'
PS - I am not familiar at all with preg_match and I am aware that wp_img_tag_add_loading_attr has been deprecated.
$bufferseems to have come out of nowhere. I thought you were telling us that we only had access to$value, $image, $context.$bufferstring?wp_img_tag_add_loading_attr()so that there is a minimal reproducible example.