WordPress 5.8+ generates WebP versions of uploaded images automatically (when the GD or Imagick extension supports it), and WordPress 6.5 added experimental AVIF support. A complete image optimisation pipeline combines format generation, quality tuning, responsive srcset attribute output, and a <picture> element fallback for maximum browser compatibility and minimum file size.
Problem: WordPress's default image handling uploads JPEG and PNG files as-is — large original images are served to all visitors, there is no automatic WebP or AVIF generation, and the theme lacks responsive image sizes appropriate for each viewport.
Solution: Add WebP conversion to the upload pipeline using wp_generate_attachment_metadata and the imagick PHP extension. Register custom image sizes with add_image_size() for each breakpoint. Use the wp_calculate_image_srcset filter to add WebP sources to srcset, and add AVIF as a progressive enhancement via a <picture> source element.
The code below enables WebP/AVIF output at the correct quality settings, adds a custom image size for above-the-fold hero images, outputs a <picture> element with AVIF and WebP sources, and defers off-screen images with native lazy loading.
NOTE: WordPress generates WebP/AVIF sub-sizes only for newly uploaded images — existing images need to be regenerated with wp media regenerate --yes (WP-CLI) after enabling the image editors; this can be a long-running operation on sites with thousands of media items, so run it during off-peak hours.