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:
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?
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:
Hope it helps!