Introduction
Website speed matters a lot for both users and search engines. One of the best ways to improve performance is by using WebP images instead of traditional formats like JPG and PNG.
In this guide, you’ll learn how to automatically convert uploaded images to WebP in WordPress using a simple code snippet.
Why Use WebP Images?
Improved user experience
Smaller file size compared to JPG/PNG
Faster page loading speed
Better SEO rankings
How It Works
We’ll add a custom function in WordPress that converts images into WebP format automatically whenever you upload them.
/**
- Convert uploaded images to WebP format automatically.
*/
add_filter(‘wp_handle_upload’, ‘convert_to_webp_on_upload’, 10, 2);
function convert_to_webp_on_upload($upload, $context) {
// Check if the upload was successful and if it’s an image
if (!isset($upload[‘file’]) || strpos($upload[‘type’], ‘image/’) !== 0) {
return $upload;
}
$file_path = $upload['file'];
$file_type = $upload['type'];
// Avoid double conversion or converting already WebP files
if ($file_type === 'image/webp') {
return $upload;
}
// Load the image based on its type
switch ($file_type) {
case 'image/jpeg':
$image = imagecreatefromjpeg($file_path);
break;
case 'image/png':
$image = imagecreatefrompng($file_path);
imagepalettetotruecolor($image); // Preserve transparency
imagealphablending($image, true);
imagesavealpha($image, true);
break;
case 'image/gif':
$image = imagecreatefromgif($file_path);
break;
default:
return $upload;
}
if (!$image) {
return $upload; // Return original if image creation fails
}
// Define the new file path with .webp extension
$webp_path = preg_replace('/\.(jpe?g|png|gif)$/i', '.webp', $file_path);
// Convert and save as WebP (Quality: 80)
if (imagewebp($image, $webp_path, 80)) {
// Remove the original file to save space
unlink($file_path);
// Update the upload array with new file details
$upload['file'] = $webp_path;
$upload['url'] = str_replace(basename($file_path), basename($webp_path), $upload['url']);
$upload['type'] = 'image/webp';
}
// Free up memory
imagedestroy($image);
return $upload;
}
