How to lazy load custom field images in wordpress

Lazy load text

WP Rocket is a great, paid-for module for improving the performance of WordPress. Their Lazy Load module improves perfomance further by online preloading images above the page fold.

I was helping a colleague to tweak the performance of a WordPress press site, when I noticed that the images were not lazy loading. It seemed like something was happening – CSS classes like “lazy” were being appended to images – but images were all preloading, as the browser developer tools highlighted.

After some digging, we eventually realised that the WP Rocket Lazy Load module re-writes the WordPress HTML output but can only do this for core features like Posts and some other plugins. The site in question was using Advanced Custom Fields and WP Rocket was not able rewrite this content.

The solution was to manually update the template, effectively replacing the need for pre-processing. Details on how to do this can be found here.

The solution was to manually update the template, effectively replacing the need for pre-processing. Details on how to do this can be found here.

In your template, you should replace:

<img
  src="<?php echo $promoImage['sizes']['YOUR_FIELD_NAME']; ?>"
  width="600"
  height="400" />

With:

<img
  src="data:image/gif;base64,R0lGODdhAQABAPAAAP///wAAACwAAAAAAQABAEACAkQBADs="
  data-lazy-src="<?php echo $promoImage['sizes']['YOUR_FIELD_NAME']; ?>"
  width="600"
  height="400" />


Sign-up for more tips on getting the most from your technology. No spam, only useful tips.