Remove src from wp_get_attachment_image

I am trying to lazyload images that are being retrieved using the following code:

<?php $args = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'posts_per_page' => -1,
'orderby'=> 'menu_order',
'order'=>'ASC', 
'post_parent' => $post->ID,
);
$images = get_posts( $args );
foreach($images as $image):
echo wp_get_attachment_image($image->ID, 'large');
endforeach;
?>

In order to use the lazy loader i need to add a data-src attribute to the img which I have done using the following code:

Read More
function alter_att_attributes_wpse_102079($attr) {
$attr['data-original'] = $attr['src'];
return $attr;
}
add_filter( 'wp_get_attachment_image_attributes',
'alter_att_attributes_wpse_102079');

This works well however, the images are still being loaded even when they are not in the viewport and this is because of the src tag still on the image I believe.

IS there any way to remove the src or replace it with the data-original instead?

Related posts

1 comment

  1. You can use wp_get_attachment_image_src instead. It returns the image data without echoing it, making build your tag easier.

    It would be something like this:

    foreach($images as $image):
        $img = wp_get_attachment_image_src($image->ID, 'large');
        echo '<img src="" data-original="'.$img[0].'" width="'.$img[1].'" height="'.$img[2].'" >';
    endforeach;
    

    Hope it helps!

Comments are closed.