a snippet to Automatically convert jpg & png & gif to webp on upload

Home » Snippets » a snippet to Automatically convert jpg & png & gif to webp on upload
0

Created with:

Visibility: 

public

Creator: Ahrale

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project
					<?php

// Convert JPG, PNG, and GIF to WebP on upload using Imagick
function atar4u_convert_images_to_webp($metadata, $attachment_id) {
    $file = get_attached_file($attachment_id);
    $file_info = wp_check_filetype($file);
    $mime_type = $file_info['type'];

    // Check if the file is a JPG, PNG, or GIF image
    if (in_array($mime_type, ['image/jpeg', 'image/png', 'image/gif'])) {
        // Create an instance of Imagick
        $image = new Imagick($file);

        // Set the output format to WebP
        $image->setFormat('webp');

        // Convert the image to WebP
        $webp_file = $file . '.webp';
        $image->writeImage($webp_file);

        // Update the attachment metadata to point to the WebP file
        $metadata['file'] = str_replace($file_info['ext'], 'webp', $metadata['file']);
        $metadata['sizes'] = [];
        $metadata['mime-type'] = 'image/webp';
    }

    return $metadata;
}
add_filter('wp_generate_attachment_metadata', 'atar4u_convert_images_to_webp', 10, 2);
				

In this snippet, we use the Imagick class to create an instance of the image and set the output format to WebP. Then, we use the writeImage method to save the converted image as a WebP file. The rest of the code remains the same, updating the attachment metadata to point to the WebP file.

Make sure you have the Imagick PHP extension installed and enabled on your server to use this code.

Register an account to save your snippets or go Pro to get more features.