Image Format Converter
Automatically convert uploaded images to WebP & AVIF, rewrite HTML output, and serve them with zero-PHP overhead via server-level redirect cascades.
Overview
Image Format Converter is a highly optimized, production-grade WordPress plugin designed to reduce page size and solve image delivery warnings in Google Lighthouse (Core Web Vitals). It translates uploaded raster images into next-generation formats (WebP and AVIF) and rewrites DOM paths dynamically—or serves them natively at the server level via Apache/Nginx—without relying on heavy third-party CDNs or cloud-based compression SaaS. Deploying from a staging environment? EZ Page Sync pairs well for pushing content to production before this plugin optimizes the incoming media.
Next-Gen Formats
Support for WebP (82% default quality) and AVIF (60% default quality) cascades. AVIF delivers up to 35% better compression rates than WebP at identical perceptual visual quality.
Zero-PHP Serving
Avoid PHP overhead entirely. By injecting custom server configuration rules, Apache and Nginx serve WebP/AVIF versions directly when client compatibility and local asset exists.
Key Features
Automatic Translation
Hooks into WordPress media metadata generators. Instantly processes uploads to generate compressed format duplicates for the main file and all thumbnail profiles.
Bulk Background Batches
Processes pre-existing media libraries in batch groups using AJAX steps. Built with a responsive, client-side progress bar and supports pause, start, and stop signals.
Smart HTML Rewriter
Parses outgoing HTML payloads during buffer cycles. Intercepts <img>, <source>, and inline CSS url() calls, swapping URLs for WebP/AVIF equivalents when client compatibility matches.
Original File Preservation
Ensures safety. Original source files are never deleted unless explicitly requested. They are safely offloaded to a designated backup folder (webp-originals/).
Lossless PNG Optimization
Provides opt-in lossless encoding parameters specifically for PNG formats to retain clean typography and alpha transparency, bypassing default lossy WebP parameters.
Size Guard Safeguards
Compares files defensively. If the resulting WebP or AVIF output is larger than the original source file, the duplicate is purged, preventing waste of disk space.
How It Works
Image Format Converter operates on a dual-phase pipeline system. The Conversion Pipeline processes the files, while the HTML Rewrite Pipeline takes care of presenting the optimized images to visitors.
Conversion Pipeline
An image is uploaded through the media library or bulk processor, which invokes the wp_generate_attachment_metadata filter hook.
The plugin checks for Imagick with WebP/AVIF support, falling back to GD, and finally to WP_Image_Editor.
If "Keep originals" is enabled, the source file is copied to the designated backup folder before compression begins.
The image is compressed into WebP/AVIF. If the file output size is larger than the original, the converted copy is immediately purged.
HTML Rewrite Pipeline
The template_redirect hook initializes PHP's output buffering callback if the active browser sends compatibility Accept headers.
The Rewriter component processes raw HTML via regular expressions, scanning for image URLs within elements like <img>, <source>, and style="...".
For each matched file URL, the rewriter verifies whether the converted WebP or AVIF asset actually exists on the local disk before rewriting.
URL extensions are swapped, and any responsive descriptors like srcset dimensions are correctly re-appended.
Technical Architecture
The plugin is organized into six core modular classes, strictly decoupled to separate settings, conversion, and output presentation:
| Class Component | Role & Functionality |
|---|---|
| WP_WebP_Optimizer\Plugin | Core bootstrap wrapper. Coordinates lifecycle hooks, registers administrative assets, triggers checks for server requirements, and coordinates hooks for image conversions and deletions. |
| WP_WebP_Optimizer\Converter | The core optimization processor. Loads raw images, coordinates library encoders (GD or Imagick), manages backup directories, compares output sizes, and updates post meta records. |
| WP_WebP_Optimizer\Rewriter | HTML template redirect hook. Listens to output buffer cycles, checks browser HTTP_ACCEPT parameters, matches image URLs, validates disk paths, and rewrites URLs with fallback cascade. |
| WP_WebP_Optimizer\BulkProcessor | Handles bulk background conversion. Manages AJAX callbacks, tracks task loops via locks and transient heartbeats, checks for user stop signals between batches, and reports progress stats. |
| WP_WebP_Optimizer\Settings | WordPress Settings API wrapper. Registers options, defines default configuration matrices, validates and clamps input fields, and renders form interfaces. |
| includes/helpers.php | Global helper utilities. Contains path helpers (e.g. wpwo_get_webp_path()), checks for browser WebP/AVIF compatibility, determines if paths reside in the uploads folder, and runs caching stats. |
Configuration Settings
| Setting Key | Default | Description |
|---|---|---|
| webp_quality | 82 | WebP lossy quality parameter. Must be between 1 and 100. |
| avif_enabled | false | Opt-in flag for AVIF output generation (requires PHP 8.1+ & Imagick 7.0+). |
| avif_quality | 60 | AVIF quality parameter. 60 provides similar visual results to WebP at quality 82. |
| auto_convert | true | Automatically trigger conversions on attachment metadata generation. |
| rewrite_html | true | Swap output path links via PHP output buffer parsing. |
| keep_originals | true | Preserves original uploaded files in the designated backup subdirectory. |
| backup_folder | 'webp-originals' | Name of the sub-folder created in the uploads folder to store backups. |
| lossless_png | false | Uses lossless conversion algorithms specifically for PNG assets. |
| skip_if_larger | true | Delete the converted asset if its file size is larger than the original. |
| cdn_base_url | '' | Optional CDN base URL to match and rewrite image assets offloaded to external hosts. |
Server-Level Serving (Zero-PHP Overhead)
For high-traffic production environments, relying on PHP's output buffering to parse and rewrite HTML is inefficient. Instead, we can bypass PHP completely for image serving. When a user requests a file like image.png, the web server (Apache or Nginx) intercepts the request, detects if the browser accepts AVIF/WebP, checks if the optimized file exists on disk, and serves it directly.
# BEGIN Image Format Converter
<IfModule mod_rewrite.c>
RewriteEngine On
# 1. Try AVIF first
RewriteCond %{HTTP_ACCEPT} image/avif
RewriteCond %{REQUEST_FILENAME} ^(.+)\.(jpe?g|png|gif|bmp)$
RewriteCond %1.avif -f
RewriteRule ^(.+)\.(jpe?g|png|gif|bmp)$ $1.avif [T=image/avif,E=WPWO_AVIF:1,L]
# 2. Fall back to WebP
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{REQUEST_FILENAME} ^(.+)\.(jpe?g|png|gif|bmp)$
RewriteCond %1.webp -f
RewriteRule ^(.+)\.(jpe?g|png|gif|bmp)$ $1.webp [T=image/webp,E=WPWO_WEBP:1,L]
</IfModule>
<IfModule mod_headers.c>
# Vary Accept ensures proxies/CDNs cache separately for AVIF, WebP, and original
Header merge Vary Accept env=WPWO_AVIF
Header merge Vary Accept env=WPWO_WEBP
</IfModule>
<IfModule mod_mime.c>
AddType image/webp .webp
AddType image/avif .avif
</IfModule>
# END Image Format Converter# Define modern image suffix map based on Accept headers
map $http_accept $modern_suffix {
default "";
"~*image/avif" ".avif";
"~*image/webp" ".webp";
}
# Match static upload images and serve next-gen duplicates
location ~* ^/wp-content/uploads/(.+)\.(jpe?g|png|gif|bmp)$ {
add_header Vary Accept;
# Try serving $1 (path) + modern suffix first, falling back to original
try_files /wp-content/uploads/$1$modern_suffix $uri =404;
expires 365d;
}Frequently Asked Questions
Does the plugin delete original files when converting?
No, by default original files are retained. The plugin moves them to a secure backup folder at /wp-content/uploads/webp-originals/ before compression. They are only deleted if you explicitly disable the "Keep originals" setting.
What happens if a browser does not support WebP or AVIF?
The HTML rewriter checks the incoming browser Accept header. If the client doesn't explicitly declare support for WebP or AVIF (like older versions of Safari or IE), the HTML output buffering returns the original JPEG/PNG URLs completely unchanged.
Why did some converted WebP/AVIF files not generate?
Image Format Converter features an automated file-size check. If the optimized WebP or AVIF file is larger than the original uncompressed source image, the plugin discards the converted copy. This commonly occurs with small, pre-optimized source PNGs or JPEGs.
Does this plugin work with CDN setups?
Yes. You can supply a "CDN Base URL" in the settings. The HTML rewriter matches static paths pointing to your CDN domains and converts those links to use the .webp or .avif extensions, matching files that have been pushed or synced to the CDN.
How do I verify server-level serving is working?
Disable the "HTML rewriting" setting. If you inspect an image in your browser developer tools, the URL will still read image.jpg. However, if you examine the Network tab response headers, you will see Content-Type: image/webp (or image/avif), proving the server is dynamically serving the optimized version transparently.
Changelog
v1.0.9
June 27, 2026Added & Fixed:
- Fixed WordPress admin panel notices (such as third-party license nags) disrupting the layout of the plugin's settings panel.
- Fixed conversion failures on palette-based index source images (PNG-8 formats and GIFs) by promoting index palettes to truecolor inside the GD conversion module.
- Added detailed error logs gated behind
WP_DEBUG_LOGthat write GD/Imagick exception errors to simplify debugging conversion failures. - Updated system requirements checks to confirm WordPress 7.0 compatibility.
v1.0.8
June 26, 2026Refined HTML Rewriting:
- Hardened the
srcsetparser to correctly loop through and rewrite every comma-separated candidate url. - Added defensive descriptor mappings. If an element lacks a width descriptor, the plugin attempts to parse and extract dimensions directly from the file name suffix (e.g.
-600x400.jpgto600w). - Added limits to responsive size candidates. Image generation size is capped relative to the maximum declared tag dimensions, saving significant CPU overhead and disk space.
v1.0.7
June 20, 2026AVIF support intro:
- Introduced full AVIF format support with options to enable AVIF and adjust AVIF compression quality in settings.
- Added a
wp_ajax_wpwo_bulk_resetaction hook to safely clear stuck lock transients. - Added safeguards to check for empty/zero-byte outputs during conversion to prevent saving corrupted assets.
- Added response filters to ensure sitemaps, JSON responses, and non-HTML assets are ignored by the HTML output rewriter.
