Home > Net >  Wordpress Remove Lazy Load from Main Product Image
Wordpress Remove Lazy Load from Main Product Image

Time:11-15

Need to prevent the main image on the product page from lazy loading.

The main product image is loaded in 'woocommerce/single-product/product-image.php'

It uses: wp_get_attachment_image( $attachment_id, $size, $icon, $attr ); to get the image.

Inside the function above, there is:

// Add `loading` attribute.
    if ( wp_lazy_loading_enabled( 'img', 'wp_get_attachment_image' ) ) {
        $default_attr['loading'] = wp_get_loading_attr_default( 'wp_get_attachment_image' );
    }

    $attr = wp_parse_args( $attr, $default_attr );

    // If the default value of `lazy` for the `loading` attribute is overridden
    // to omit the attribute for this image, ensure it is not included.
    if ( array_key_exists( 'loading', $attr ) && ! $attr['loading'] ) {
        unset( $attr['loading'] );
    }

So clearly it's possible to not lazy load it, but I just don't fully understand how I can do this?

CodePudding user response:

one way you might be able to do this is to use the wp_get_attachment_image_attributes filter like below:

<?php

add_filter("wp_get_attachment_image_attributes", function($attr, $attachment, $size) {
    $first_image_post_id = 'ID of the image you want to remove the lazy attr';
    
    if ( $attachment->ID === $first_image_post_id ) {
        unset( $attr['loading'] );
    }

    return $attr;
}, 10, 3);

More info on the WP docs: https://developer.wordpress.org/reference/hooks/wp_get_attachment_image_attributes/

CodePudding user response:

add_filter( 'wp_get_attachment_image_attributes', 'remove_img_attr', 10, 2 );
function remove_img_attr( $attr, $attachment ) {
    unset( $attr['id'] );
    return $attr;
}
  • Related