Responsive images in WordPress: srcset, sizes and lazy loading
Images are usually the heaviest part of a page. For responsive images in WordPress, core already does a lot of the work, but a few details decide whether that work pays off.
Register the sizes you actually use
If a card always shows images at 16:10, register a cropped size for it instead of serving the full upload:
add_image_size( 'card', 800, 500, true );
Let WordPress write the srcset
wp_get_attachment_image() outputs srcset with every generated size of the same aspect ratio. The browser then picks the smallest file that fits.
echo wp_get_attachment_image(
$image_id,
'card',
false,
array(
'sizes' => '(min-width: 1024px) 380px, 100vw',
)
);
Get the sizes attribute right
sizes tells the browser how wide the image will be displayed before the CSS loads. If you leave a generic value, the browser may download a much larger file than needed. Describe your real layout: how wide is this image at each breakpoint?
Lazy load below the fold, not above it
WordPress adds loading="lazy" to most images automatically. That is right for content further down the page, but the main image at the top of the page should load immediately:
the_post_thumbnail( 'large', array(
'loading' => 'eager',
'fetchpriority' => 'high',
) );
This helps Largest Contentful Paint, one of the Core Web Vitals.
Always set width and height
WordPress includes width and height attributes on attachment images. Keep them. They let the browser reserve space and prevent layout shift while the image loads.