Images are typically the largest assets on a WordPress page. A single unoptimised hero image can weigh more than all the JavaScript on the page combined. Here’s how to handle image optimisation at every stage: upload, serving, and markup.
Problem: Unoptimised images are typically the largest assets on a WordPress page — accounting for most of the page weight and significantly slowing load times on mobile connections.
Solution: Combine multiple optimisation layers: set define('IMAGE_EDIT_OVERWRITE', true) and tune Imagick quality in wp-config.php, use a compression plugin like ShortPixel to convert existing uploads to WebP, and verify that loading="lazy" is applied to below-the-fold images.
1. Generate only the image sizes you actually use. WordPress creates multiple image sizes on upload. Register only the ones your theme needs and remove the defaults you don't use:
// Register a custom image size
add_image_size( 'hero-large', 1600, 600, true ); // hard crop
add_image_size( 'card-thumb', 400, 300, true );
// Remove default sizes you don't use (saves disk space and upload time)
add_filter( 'intermediate_image_sizes_advanced', function( $sizes ) {
unset( $sizes['medium_large'] ); // 768px — rarely used
return $sizes;
} );
2. Use responsive images in templates. WordPress adds srcset and sizes attributes automatically when you use wp_get_attachment_image():
// Output a responsive image — WordPress generates srcset automatically
echo wp_get_attachment_image(
get_post_thumbnail_id(),
'hero-large',
false,
[ 'class' => 'hero-image', 'loading' => 'lazy' ]
);
3. Lazy-load images below the fold. The loading="lazy" attribute is supported in Chrome 76+ and tells the browser to defer loading images that are not in the viewport. WordPress 5.5 added this automatically, but you can backport it to earlier versions:
// Add loading="lazy" to all post content images (WordPress < 5.5)
add_filter( 'the_content', function( $content ) {
return str_replace( '<img ', '<img loading="lazy" ', $content );
} );
4. Compress images on upload using a plugin like EWWW Image Optimizer (runs locally, no API key needed) or ShortPixel. Alternatively, compress images before uploading using tools like imagemin or Squoosh.
NOTE: Regenerate thumbnail sizes after changing add_image_size() calls. Install the Regenerate Thumbnails plugin, or run wp media regenerate --yes via WP-CLI. Without regenerating, existing images won't be available in the new dimensions.