0

I have a callback applied to wp_get_attachment_image_attributes to add attributes to the generated image html.

function add_lazyload_to_attachment_image($attr, $attachment)
{
    if (strpos($attr['class'], 'lazyload') !== false) {
        $attr['data-src'] = $attr['src'];

        if (isset($attr['srcset'])) {
            $attr['data-srcset'] = $attr['srcset'];
            $attr['data-sizes'] = "auto";
            $attr['srcset'] = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
        }
    }

    return $attr;
}
add_filter('wp_get_attachment_image_attributes', 'add_lazyload_to_attachment_image', 30, 2);

But the function does not get applied some custom image sizes. This filter works for the default image sizes present in Wordpress.

I want this filter to work for all custom image sizes. Please help.

  • All your image sizes have the lazyload class? – MikeNGarrett Apr 5 at 14:10
  • Yes. @MikeNGarrett – besrabasant Apr 5 at 15:35
  • The code above works for me. Can you show how you're calling the image? For example, I'm using echo wp_get_attachment_image( get_post_thumbnail_id(), 'full', false, array( 'class' => 'lazyload' ) ); – MikeNGarrett Apr 5 at 15:52
  • wp_get_attachment_image( get_post_thumbnail_id(), 'property-thumb', false, array( 'class' => 'lazyload' ) ); where property-thumb is a custom image size of 540 x 380 I have added. – besrabasant Apr 5 at 17:31
  • Wow almost exactly the same. I would look into other plugins or functionality that's hooking in to the image output. This works as you intended with WordPress core. – MikeNGarrett Apr 5 at 18:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.