LazyLoading Images

Howdy, folks!

I’m having trouble finding the “Wordpress-y” way of modifying the markup of the <img> tags in a given post.

For context, I’m trying to integrate into a theme I’m developing, and as such I need to replace every image tag’s src attribute with data-src.

I tried hooking into the wp_get_attachment_image_attributes filter, but that didn’t seem to do the trick.

Has anyone solved this problem?

Hey @mattrothenberg,

This is more of a general WordPress question than a Sage question, but it may be a little challenging to filter the HTML used for images in the body of posts, because after you insert it into the post content (e.g., using the visual editor), the HTML has already been generated.

If the post doesn’t exist yet or you can reinsert the images (i.e., you’re not dealing with a large preexisting content library), you might be able to use this filter:

But besides having to update any existing content, filtering it there might mean that your images don’t show up in the editor unless you also use the lazy loader on the editor–not ideal.

To avoid that, you would probably need to filter the_content, parse the HTML to find images, and replace the image markup with the modified markup you need.

To keep things simple, I might first try using an existing solution like this plugin:

if you don’t want to use a plugin, you can probably find examples of people filtering image tags in the_content to help avoid having to entirely reinvent the wheel.

– Matt

1 Like

@mmirus Thanks for the prompt reply, and apologies for posting in the wrong forum.

This is super helpful. I’ll try filtering the_content.


1 Like