Last active
March 16, 2020 04:27
-
-
Save fumikito/b58ff5ec5c6d46a91555e8c0ee4ea925 to your computer and use it in GitHub Desktop.
Add lazy attributes to all img tags in WordPress.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Add loading="lazy" and decodiing="async" | |
* | |
* @see https://spelldata.co.jp/blog/blog-2019-12-19.html | |
*/ | |
/** | |
* Start buffer for img attributes. | |
*/ | |
add_action( 'wp_head', function() { | |
ob_start(); | |
}, 9999 ); | |
/** | |
* Replace img tag and output everything. | |
*/ | |
add_action( 'wp_footer', function() { | |
$body = ob_get_contents(); | |
$replaced = preg_replace_callback( '#<img([^>]+)>#u', function( $matches ) { | |
list( $match, $attr ) = $matches; | |
foreach ( [ | |
'decoding' => 'async', // This line might be meaningless. | |
'loading' => 'lazy', | |
] as $key => $val ) { | |
if ( false !== strpos( $attr, $key . '=' ) ) { | |
// If already added, skip. | |
continue; | |
} | |
$attr = sprintf( ' %s="%s"%s', $key, $val, $attr ); | |
} | |
return sprintf( '<img%s>', $attr ); | |
}, $body ); | |
ob_end_clean(); | |
echo $replaced; | |
}, 9999 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment