Skip to content

Instantly share code, notes, and snippets.

@katsar0v
Last active February 16, 2023 02:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save katsar0v/8c5e1b3ab1f28ea3c81c03efbeea7c59 to your computer and use it in GitHub Desktop.
Save katsar0v/8c5e1b3ab1f28ea3c81c03efbeea7c59 to your computer and use it in GitHub Desktop.
Create WebP Copy In WordPress
<?php
function generate_webp_from_file($file, $compression_quality = 80) {
// check if file exists
if (!file_exists($file)) {
return false;
}
// If output file already exists return path
$output_file = $file . '.webp';
if (file_exists($output_file)) {
return $output_file;
}
$file_type = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if (function_exists('imagewebp')) {
switch ($file_type) {
case 'jpeg':
case 'jpg':
$image = imagecreatefromjpeg($file);
break;
case 'png':
$image = imagecreatefrompng($file);
imagepalettetotruecolor($image);
imagealphablending($image, true);
imagesavealpha($image, true);
break;
case 'gif':
$image = imagecreatefromgif($file);
break;
default:
return false;
}
// Save the image
$result = imagewebp($image, $output_file, $compression_quality);
if (false === $result) {
return false;
}
// Free up memory
imagedestroy($image);
return $output_file;
} elseif (class_exists('Imagick')) {
if ($file_type !== 'png') {
return false;
}
$image = new Imagick();
$image->readImage($file);
if ($file_type === 'png') {
$image->setImageFormat('webp');
$image->setImageCompressionQuality($compression_quality);
$image->setOption('webp:lossless', 'true');
}
$image->writeImage($output_file);
return $output_file;
}
return false;
}
/**
* Generate .webp copy from each size when an attachment is uploaded
*/
add_action( 'wp_generate_attachment_metadata', function( $meta, $id, $content ) {
$upload_dir = wp_get_upload_dir()['basedir'] . '/';
$file = $upload_dir . $meta['file'];
generate_webp_from_file( $file );
foreach( $meta['sizes'] as $key => $file ) {
$path = wp_get_upload_dir()['path'] . '/' . $file['file'];
generate_webp_from_file( $path );
}
return $meta;
}, 10, 3 );
/**
* Delete the all .webp copies
*/
add_action( 'delete_attachment', function( $id, $post ) {
$file = get_attached_file( $id );
$original_webp = "$file.webp";
if( file_exists( $original_webp ) ) {
unlink( $original_webp );
}
$meta = wp_get_attachment_metadata( $id );
foreach( $meta['sizes'] as $key => $file ) {
$path = wp_get_upload_dir()['path'] . '/' . $file['file'];
$webp_file = "$path.webp";
if( file_exists( $webp_file ) ) {
unlink( $webp_file );
}
}
}, 10, 2);
@heyjoecampbell
Copy link

heyjoecampbell commented Feb 15, 2023

Excellent snippet - I have one request if possible:
The metadata is lost during the Imagick conversion —> p‬lease retain all metadata

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment