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 https://github.com/verlok/lazyload into a theme I’m developing, and as such I need to replace every image tag’s
src attribute with
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?
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: https://developer.wordpress.org/reference/hooks/image_send_to_editor/.
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: https://wordpress.org/plugins/a3-lazy-load/.
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.
@mmirus Thanks for the prompt reply, and apologies for posting in the wrong forum.
This is super helpful. I’ll try filtering