Boost Your WordPress Site Speed: Automatically Convert Newly Uploaded Images to WebP Format

To convert any image type uploaded to a WordPress site to WebP, you can create a custom plugin or add the following code snippet to your theme’s functions.php file. This snippet utilizes the wp_handle_upload filter to convert uploaded images to WebP format using the Imagick extension (if available).

First, ensure you have the Imagick extension installed and enabled on your server. Then, you can use the following code:

function convert_image_to_webp($upload) {
    $file_path = $upload['file'];
    $file_type = $upload['type'];

    // Check if the file is an image
    if (strpos($file_type, 'image') !== false) {
        // Check if Imagick is available
        if (extension_loaded('imagick')) {
            $image = new Imagick($file_path);
            $webp_path = preg_replace('/\.[^.]+$/', '.webp', $file_path);

            // Update the file path and type
            $upload['file'] = $webp_path;
            $upload['url'] = preg_replace('/\.[^.]+$/', '.webp', $upload['url']);
            $upload['type'] = 'image/webp';

            // Remove the original file

    return $upload;
add_filter('wp_handle_upload', 'convert_image_to_webp');

Hook into wp_handle_upload: The wp_handle_upload filter is used to process the file after it has been uploaded.
Check if the file is an image: The code checks if the uploaded file is an image by inspecting the MIME type.
Convert the image to WebP: If the Imagick extension is available, the image is loaded, converted to WebP format, and saved with a .webp extension.
Update the file path and type: The file path and URL are updated to reflect the new WebP file. The original image file is then deleted.

Important Notes:
Imagick Extension: This code snippet requires the Imagick extension to be installed and enabled on your server. If Imagick is not available, the conversion will not happen.
Backup Files: Always back up your files before making changes to your theme’s functions.php file or any plugin files.
Testing: Test this code on a staging site before deploying it to your live site to ensure it works as expected and does not cause any issues.

Leave the first comment