Created
November 19, 2024 01:22
-
-
Save pedrorvidal/19b0878f0feb73e70edf5dcbdde479b4 to your computer and use it in GitHub Desktop.
Convert images to .webp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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