Skip to content

Instantly share code, notes, and snippets.

@vyskoczilova
Last active January 19, 2024 12:24
Show Gist options
  • Save vyskoczilova/d5a66d3578c01ea639c74696dcf9a636 to your computer and use it in GitHub Desktop.
Save vyskoczilova/d5a66d3578c01ea639c74696dcf9a636 to your computer and use it in GitHub Desktop.
Decoding async issue
<?php
add_filter('wp_img_tag_add_decoding_attr', '__return_false');
<?php
/**
* @snippet Remove decoding=async when fetchpriority=high, loading=eager in rendered HTML globally
* @article https://kybernaut.cz/en/clanky/the-unintended-consequences-of-decodingasync-on-your-wordpress-sites-lcp/
* @author Karolína Vyskočilová
* @compatible Wordpress 6.1 and greater
* @donate $9 https://www.paypal.com/paypalme/KarolinaVyskocilova
*/
add_filter( 'wp_content_img_tag', function( $filtered_image, $context, $attachment_id ) {
if ( false !== strpos( $filtered_image, 'loading="eager"' ) || false !== stripos( $filtered_image, 'fetchpriority="high"' ) ) {
$filtered_image = str_replace( ' decoding="async"', '', $filtered_image );
}
return $filtered_image;
}, 10, 3 );
<?php
/**
* @snippet Remove decoding=async when fetchpriority=high, loading=eager or your custom class from WP handled images
* @article https://kybernaut.cz/en/clanky/the-unintended-consequences-of-decodingasync-on-your-wordpress-sites-lcp/
* @author Karolína Vyskočilová
* @compatible Wordpress 6.1 and greater
* @donate $9 https://www.paypal.com/paypalme/KarolinaVyskocilova
*/
add_filter( 'wp_get_attachment_image_attributes', function( $attributes ) {
if ( isset( $attributes['fetchpriority'] ) && 'high' === $attributes['fetchpriority']
|| isset( $attributes['loading'] ) && 'eager' === $attributes['loading']
|| isset( $attributes['class'] ) && false !== strpos( $attributes['class'], 'your-custom-hero-image-class' )
) {
unset( $attributes['decoding'] );
}
return $attributes;
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment