How to Automatically Convert Uploaded Images to WebP Format in WordPress ?

While JPEG, PNG, and GIF remain widely used in WordPress, their larger file sizes can subtly impact page load speed, server storage, and overall site performance.

WebP is an image format that makes your pictures smaller without losing quality, helping your website load faster and use less storage. By converting images to the modern WebP format during upload, you can maintain image quality and improve site performance, making it ideal for WordPress websites.

Solution: Automatically Convert Uploaded Images to WebP Format in WordPress

The code will automatically convert newly uploaded JPEG, PNG, or GIF images to WebP format in WordPress. Existing images in your media library will remain unchanged.

add_filter('wp_handle_upload', 'ts_handle_upload_convert_to_webp');

function ts_handle_upload_convert_to_webp($upload) {
    if (in_array($upload['type'], ['image/jpeg', 'image/png', 'image/gif'])) {
        $file_path = $upload['file'];

        if (extension_loaded('imagick') || extension_loaded('gd')) {
            $image_editor = wp_get_image_editor($file_path);

            if (!is_wp_error($image_editor)) {
                $file_info    = pathinfo($file_path);
                $dirname      = $file_info['dirname'];
                $filename     = $file_info['filename'];
                $def_filename = wp_unique_filename($dirname, $filename . '.webp');
                $new_file_path = $dirname . '/' . $def_filename;

                $saved_image = $image_editor->save($new_file_path, 'image/webp');

                if (!is_wp_error($saved_image) && file_exists($saved_image['path'])) {
                    // Update the upload data to use the WebP image
                    $upload['file'] = $saved_image['path'];
                    $upload['url']  = str_replace(basename($upload['url']), basename($saved_image['path']), $upload['url']);
                    $upload['type'] = 'image/webp';

                    // Optionally delete the original file
                    @unlink($file_path);
                }
            }
        }
    }

    return $upload;
}

Output

After uploading a product or media image, the file is automatically converted to WebP, and you can verify this by checking the attachments in the Media Library to see the WebP file type.