Skip to content

Instantly share code, notes, and snippets.

@pedrorvidal
Created November 19, 2024 01:22
Show Gist options
  • Save pedrorvidal/19b0878f0feb73e70edf5dcbdde479b4 to your computer and use it in GitHub Desktop.
Save pedrorvidal/19b0878f0feb73e70edf5dcbdde479b4 to your computer and use it in GitHub Desktop.
Convert images to .webp
<?php
add_filter('wp_handle_upload', 'convert_to_webp', 10, 2);
function convert_to_webp($upload, $context) {
$file_path = $upload['file'];
$file_info = pathinfo($file_path);
$extension = strtolower($file_info['extension']);
$allowed_extensions = ['jpeg', 'jpg', 'png', 'gif'];
if (in_array($extension, $allowed_extensions)) {
$image = null;
switch ($extension) {
case 'jpeg':
case 'jpg':
$image = imagecreatefromjpeg($file_path);
break;
case 'png':
$image = imagecreatefrompng($file_path);
break;
case 'gif':
$image = imagecreatefromgif($file_path);
break;
}
if ($image) {
$webp_path = $file_info['dirname'] . '/' . $file_info['filename'] . '.webp';
if (imagewebp($image, $webp_path, 80)) {
imagedestroy($image);
unlink($file_path);
$upload['file'] = $webp_path;
$upload['url'] = str_replace($file_info['basename'], $file_info['filename'] . '.webp', $upload['url']);
$upload['type'] = 'image/webp';
}
}
}
return $upload;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment