A Lighthouse audit on your WooCommerce storefront comes back with “serve images in next-gen formats — estimated savings 1.8s on LCP.” You install a WebP plugin, the dashboard says “conversion complete,” and the audit doesn’t move. The browser is still loading JPEGs because the <img> tag never references the WebP, or it does but the WebP is bigger than the JPEG, or the conversion silently skipped half the library because of a memory limit. The conversion pipeline is rarely the hard part. The hard part is deciding when conversion runs, which engine does the work, and how the served URL gets rewritten.
What’s happening
A WebP/AVIF pipeline has three moving pieces, and each one has decisions:
1. The encoder. Two options on the host:
- ImageMagick (
convert/magick) with WebP and AVIF delegates. Universally available, well-documented, slow on AVIF. Memory profile is generous — a 50MP source can spike 600MB+ during encode. - libvips (
vips/vipsthumbnail). Streaming architecture, 5-10x faster than ImageMagick on the same hardware, fraction of the memory. AVIF support vialibheif/aom. The PHP bridge isphp-vips, not native to WordPress core.
For a site converting tens of thousands of images, libvips is the only choice that fits in a reasonable encode budget. For a site converting hundreds, ImageMagick is fine and avoids an extra dependency.
2. When conversion runs. Three patterns:
- Upload-time.
add_filter('wp_handle_upload', ...)triggers conversion as part of the upload request. User waits for the encode. Memory peaks during user-facing requests. Simplest mental model; worst tail latency. - Async upload-time. Schedule a wp-cron event right after upload. User completes upload; encode runs in the next cron tick. Decoupled from the request; depends on cron being healthy.
- On-demand at first request. Web server (nginx, Apache, LiteSpeed) catches a 404 on
image.webp, runs the encoder, writes the file, redirects the request. Lazy; only encodes what’s actually requested; first hit on every image is slow.
For libraries with high publish rate and broad page coverage, async upload-time is the right default. For libraries where 80% of attachments are never displayed (large editorial archives), on-demand wins.
3. URL rewriting. WordPress doesn’t natively know about WebP. The <img> tag still references the JPEG. Three rewrite strategies:
<picture>tag substitution. The plugin filtersthe_contentandwp_get_attachment_imageto wrap<img>in<picture><source srcset="…webp"></source><img></picture>. Most compatible. Breaks themes that style<img>with positional selectors.- Server-side accept-header sniffing. Nginx checks
Accept: image/webpand serves.webpfrom the same URL. Transparent to WordPress. CDN-hostile — every CDN cache key now varies on Accept header. - CDN-level image transformation. Cloudflare Image Resizing, BunnyCDN Optimizer, KeyCDN Image Processing. Offloads conversion entirely; the plugin only manages metadata. Per-request cost; bandwidth and CPU savings often outweigh the cost.
The conversion ratio matters too. WebP typically saves 25-35% vs JPEG at the same perceived quality. AVIF saves 40-50% vs JPEG but encodes 10-20x slower. The break-even between “spending CPU to convert” and “spending bandwidth to serve” depends on your traffic; for a busy storefront, AVIF pays off within weeks.
How to verify
Check what’s installed and what works:
# Encoder availability
convert -version | grep -i webp
convert -list format | grep -iE 'webp|avif|heif'
vips --version 2>&1 | head -3
vips list classes 2>&1 | grep -iE 'webp|heif'
# PHP module check
php -m | grep -iE 'imagick|vips|gd'
php -r 'echo "GD WebP: ".((gd_info()["WebP Support"] ?? false) ? "yes" : "no").PHP_EOL;'
For an existing pipeline, see what’s actually being generated:
# Count WebP/AVIF coverage vs source
cd /home/acmewp/public_html/wp-content/uploads
jpg=$(find . -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.png' | wc -l)
webp=$(find . -iname '*.webp' | wc -l)
avif=$(find . -iname '*.avif' | wc -l)
echo "JPG/PNG: $jpg | WebP: $webp | AVIF: $avif"
# Find sources that have no WebP companion
find . \( -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.png' \) | while read f; do
webp="${f%.*}.webp"
[ -f "$webp" ] || echo "MISSING WebP: $f"
done | head -30
Test what the browser actually receives:
# Force a WebP-capable request
curl -sI -H "Accept: image/webp,image/*" https://example.com/wp-content/uploads/2026/05/hero.jpg \
| grep -iE 'content-type|content-length'
# Same URL, no Accept hint
curl -sI https://example.com/wp-content/uploads/2026/05/hero.jpg \
| grep -iE 'content-type|content-length'
If both return image/jpeg, the rewrite layer is not engaged. If only the first returns image/webp and Vary: Accept is in the response, accept-header sniffing is on (mind the CDN cache).
The fix
A pipeline that works at scale, in priority order:
Step 1 — Pick the encoder, install once. On AlmaLinux/RHEL 9:
dnf install -y vips vips-tools vips-devel libheif libheif-tools
pecl install vips
echo 'extension=vips.so' > /etc/php.d/40-vips.ini
# Verify libvips can produce AVIF
echo 'test' | vips copy - /tmp/test.avif 2>&1 || echo "AVIF encode missing"
Step 2 — Async upload-time encode. Hook into wp_generate_attachment_metadata and schedule a per-attachment job:
// mu-plugins/wp-media-encode.php
add_filter('wp_generate_attachment_metadata', function($metadata, $attachment_id) {
wp_schedule_single_event(time() + 5, 'sh_encode_modern', [$attachment_id]);
return $metadata;
}, 10, 2);
add_action('sh_encode_modern', function($attachment_id) {
$file = get_attached_file($attachment_id);
if (!$file || !file_exists($file)) return;
$sizes = wp_get_attachment_metadata($attachment_id)['sizes'] ?? [];
$dir = dirname($file);
$targets = [$file];
foreach ($sizes as $size) {
$targets[] = $dir . '/' . $size['file'];
}
foreach ($targets as $src) {
$base = preg_replace('/\.(jpe?g|png)$/i', '', $src);
if (!file_exists($base . '.webp')) {
exec(sprintf('vipsthumbnail %s -o %s.webp[Q=80,strip] 2>&1',
escapeshellarg($src), escapeshellarg($base)));
}
if (!file_exists($base . '.avif')) {
exec(sprintf('vipsthumbnail %s -o %s.avif[Q=60,effort=4] 2>&1',
escapeshellarg($src), escapeshellarg($base)));
}
}
}, 10, 1);
For backfill on an existing library, drive it via WP-CLI rather than blasting cron:
wp post list --post_type=attachment --post_mime_type=image --format=ids | \
xargs -n 1 -P 4 -I {} wp eval "do_action('sh_encode_modern', {});"
The -P 4 keeps four concurrent encodes; tune to CPU count minus one. On a 16-core box, 12-14 parallel encodes saturate libvips comfortably.
Step 3 — Pick the rewrite strategy. For most sites, <picture> tag rewrite is the safest because it survives CDN cache keys without Vary:
// mu-plugins/wp-media-picture.php
add_filter('wp_get_attachment_image', function($html, $attachment_id, $size) {
$src = wp_get_attachment_image_url($attachment_id, $size);
if (!$src) return $html;
$webp = preg_replace('/\.(jpe?g|png)$/i', '.webp', $src);
$avif = preg_replace('/\.(jpe?g|png)$/i', '.avif', $src);
$webp_exists = file_exists(str_replace(content_url(), WP_CONTENT_DIR, $webp));
$avif_exists = file_exists(str_replace(content_url(), WP_CONTENT_DIR, $avif));
if (!$webp_exists && !$avif_exists) return $html;
$sources = '';
if ($avif_exists) $sources .= '<source srcset="' . esc_url($avif) . '" type="image/avif">';
if ($webp_exists) $sources .= '<source srcset="' . esc_url($webp) . '" type="image/webp">';
return '<picture>' . $sources . $html . '</picture>';
}, 10, 3);
For sites already behind a smart CDN (Cloudflare with Polish, BunnyCDN Optimizer), skip the local conversion entirely and let the CDN handle it. Storage cost on the origin stays low; transformation runs at the edge.
Step 4 — Storage budget. Three encodes per source (.jpg, .webp, .avif) per registered thumbnail size adds up. For a library with 5 sizes per attachment, you go from 5 files to 15 files. If origin storage is constrained, generate WebP only for sizes >= medium and skip thumbnails. Add keep_local => false and offload everything to object storage if disk is the binding constraint.
Stack Harbor sets up image pipelines (encode + rewrite + CDN) as part of enterprise WordPress support — and operates the conversion infrastructure under Managed Cloud Ops so the encoder version, the cron, and the storage budget stay maintained. If your Lighthouse score keeps flagging the same images, book an audit.