2

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?

1 Answer 1

0

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!

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.