Hello everyone! Today I’m gonna share a tutorial on how to add attachment-ID as class to an attached image. I just re-share what I found on the internet, the concept is originally written by Attila from LetsWP.io who wrote it in this article.
At first I were having a problem with inconsistent Largest Contentful Paint (LCP) metric. I found out that the LCP area is changing along with the browser loading time. It was finally fixed by adding height value to elements on the above the fold area.
At the time of fixing it, I found an image considered as an element contributing to the LCP metric. No problem, I can add height and width to its css style, inline.
However, it still complained that LCP metric is too high. I tried everything, until I realized, the image is being lazy-loaded. Okay, let’s fix it, exclude the image from being lazy-loaded.
I’m using A3 Lazy Load plugin by a3rev.
A3 Lazy Load is a great plugin, it can work alongside autoptimize, it can lazy load iframes too. However, it can exclude images from being lazy-loaded by its class only, unlike autoptimize which can exclude by filename.
As Attila said in his post, images attached on a post that is created programmatically (means built by a page builder such as elementor, beaver, etc.) will not include its attachment ID as its class. This is quite problematic when using a3 Lazy Load. Like I said, it can only exclude by its class.
To resolve the issue above, add this to your theme’s functions.php or create one snippet on Code Snippets :
/**
Add attachment ID class to images
*
@param array $attr Array of attributes.
@param object $attachment Attachment Post object, instance of WP_Post class.
@return array Image attributes array.
*/
function lwp_attachment_id_class( $attr, $attachment ) {
$class_attr = isset( $attr['class'] ) ? $attr['class'] : '';
$has_class = preg_match(
'/wp-image-[0-9]+/',
$class_attr,
$matches
);
// Check if the image is missing the class
if ( !$has_class ) {
$class_attr .= sprintf( ' wp-image-%d', $attachment->ID );
// Use ltrim to to remove leading space if necessary
$attr['class'] = ltrim( $class_attr );
}
return $attr;
}
add_filter(
'wp_get_attachment_image_attributes', 'lwp_attachment_id_class', 10, 2
);