phpwordpressif-statementlazy-loadingpreg-match

Skip Lazy Loading by Image Class Added to Figure Element in WordPress


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.


Solution

  • Here's the solution:

    function add_loading_attr_to_img_in_figure($content) {
        // Define the pattern to match a <figure> with the specific class
        $pattern = '/(<figure[^>]*class="[^"]*eager-load[^"]*"[^>]*>)(.*?)(<img[^>]+>)(.*?<\/figure>)/is';
    
        // Define the replacement to add the loading="eager" attribute to the <img> tag
        $replacement = '$1$2<img loading="eager"$3$4';
    
        // Use preg_replace to modify the content
        $content = preg_replace($pattern, $replacement, $content);
    
        return $content;
    }
    
    // Add the filter for the_content to modify images in post content
    add_filter('the_content', 'add_loading_attr_to_img_in_figure');