Convert JPG to WebP on the Fly

Boost performance without changing your workflow.
The “Convert JPG to WebP on the Fly” plugin automatically converts .jpg images to .webp format and serves them directly to users — no manual uploads or additional plugins required.
How It Works
Every time a .jpg image is found in your post content, the plugin checks if a .webp version exists in the same location:
• If a WebP version already exists, it gets served instead of the JPG.
• If not, the plugin generates a WebP copy on the fly (at 75% quality), saves it in the same folder, and serves it automatically.
Key Features
• Automatic WebP conversion — no manual steps needed
• Works with images inside post content
• Improves loading speed and PageSpeed scores
• Lightweight, no settings or UI bloat
• No external services or APIs required
Requirements
• WordPress 5.8 or higher
• PHP 7.4 or higher
• Your server must support the GD library with WebP support
Use Case
This plugin is ideal for performance-focused WordPress sites that want to use modern image formats without restructuring the entire media workflow. Great for blogs, portfolios, and lightweight content sites where every millisecond counts.
Want to serve WebP images efficiently without changing how you upload or manage content?
This plugin makes it effortless.
<?php
/**
* Plugin Name: Convert JPG to WebP on the fly
* Plugin URI: https://customwp.net/
* Description: Convert JPG images to WebP.
* Version: 1.1
* Requires at least: 5.8
* Requires PHP: 7.4
* Author: Torsten Wenzel
* Author URI: https://customwp.net
* License: GPLv2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
*/
function serve_webp_image($image_url) {
$upload_dir = wp_get_upload_dir();
$image_path = str_replace($upload_dir['baseurl'], $upload_dir['basedir'], $image_url);
if (pathinfo($image_path, PATHINFO_EXTENSION) === 'jpg') {
$webp_path = str_replace('.jpg', '.webp', $image_path);
if (file_exists($webp_path)) {
return str_replace('.jpg', '.webp', $image_url);
} else {
$image = imagecreatefromjpeg($image_path);
if ($image !== false) {
if (imagewebp($image, $webp_path, 75)) {
imagedestroy($image);
return str_replace('.jpg', '.webp', $image_url);
}
}
}
}
return $image_url;
}
function replace_jpg_with_webp($content) {
$pattern = '/https?:\/\/[^\"\'\s]+\.jpg/';
return preg_replace_callback($pattern, function ($matches) {
return serve_webp_image($matches[0]);
}, $content);
}
add_filter('the_content', 'replace_jpg_with_webp');