Niresh
Niresh

Reputation: 145

Lazy Load Background Images Wordpress

I want to lazy load background images so i need to convert

<div class="post-header post-tp-11-header" style="background-image: url(https://cdn.guest.blog/wp-content/uploads/2017/01/A-Beautiful-Message-for-Anyone-Who-is-Searching-For-Love-750x430.jpg);">

to

<div class="post-header post-tp-11-header" data-original="https://cdn.guest.blog/wp-content/uploads/2017/01/A-Beautiful-Message-for-Anyone-Who-is-Searching-For-Love-750x430.jpg">

[style may contain two or more attributes, only the background image attribute should be removed ]

Which i have partially got working using the following PHP Source but it only works with a tags it is not working with any div

static function add_background_placeholders( $content ) {
    // Don't lazyload for feeds, previews, mobile
    if( is_feed() || is_preview() || ( function_exists( 'is_mobile' ) && is_mobile() ) )
        return $content;
    // Don't lazy-load if the content has already been run through previously
    if ( false !== strpos( $content, 'data-background' ) )
        return $content;
    preg_match_all('~\bstyle=(\'|")(.*?)background(-image)?\s*:(.*?)\(\s*(\'|")?(?<image>.*?)\3?\s*\)~i',$content,$matches);

    if( empty( $matches ) ) return $content;

    foreach( $matches[0] as $match ){
         preg_match('~\bbackground(-image)?\s*:(.*?)\(\s*(\'|")?(?<image>.*?)\3?\s*\)~i',$match,$bg);              
         $bg_less_match = str_replace( $bg[0], '', $match );             
         $data_match = 'data-background="'.$bg['image'].'" '.$bg_less_match;
         $content = str_replace( array($match.';', $match), array( $data_match, $data_match), $content);
    }

  return $content;
}

I have tried my best to sort it out but couldn't find a solution

[Mods: Please correct this questions if there anything wrong]

Upvotes: 1

Views: 1339

Answers (1)

Reece
Reece

Reputation: 396

The function in your question will actually search through div's by default. I have tested it here: https://regex101.com/r/HunEXt/1.

The problem may be that you are not passing the correct content as a parameter.


Also, make sure you are changing the line

$data_match = 'data-background="'.$bg['image'].'" '.$bg_less_match;

to

$data_match = 'data-original="'.$bg['image'].'" '.$bg_less_match;

to get your desired data attribute.

Upvotes: 1

Related Questions