Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment