Performance PHP Beginner

Don’t Lazy-Load Images Above the Fold

Tell WordPress how many images at the top of each page to load straight away instead of lazily, to speed up your hero image.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 3 lines
add_filter( 'wp_omit_loading_attr_threshold', function (): int {
	return 2; // The first 2 content images load eagerly.
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

Lazy loading delays images until they scroll into view. That’s great for images further down, but it slows down images visible straight away, like a hero image, and hurts Largest Contentful Paint. WordPress already skips lazy loading for the first content image. This snippet lets you change how many.

How it works

WordPress counts the images it outputs in the main content. For the first N, set by wp_omit_loading_attr_threshold, it leaves out loading="lazy", and gives the first large one fetchpriority="high". Every image after that is lazy-loaded as usual.

Things to watch

  • Set it to the number of images that are typically visible without scrolling. Too high a number loads images people may never see.
  • Images printed by page builders or theme code outside WordPress’s image functions aren’t counted. Many builders have their own setting.

How to test it

View the source of a post with several images. The first two &lt;img&gt; tags should have no loading="lazy" attribute; later ones should.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only