Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save WP-Panda/bdc6941a90e3307cf6903101caf16fad to your computer and use it in GitHub Desktop.
Save WP-Panda/bdc6941a90e3307cf6903101caf16fad to your computer and use it in GitHub Desktop.
/**
* Генерирует webp копии изображений сразу после загрузки изображения в медиабиблиотеку
*
* - новые файлы сохраняет с именем name.ext.webp, например, thumb.jpg.webp
*/
function gt_webp_generation($metadata) {
$uploads = wp_upload_dir(); // получает папку для загрузки медиафайлов
$file = $uploads['basedir'] . '/' . $metadata['file']; // получает исходный файл
$ext = wp_check_filetype($file); // получает расширение файла
if ( $ext['type'] == 'image/jpeg' ) { // в зависимости от расширения обрабатаывает файлы разными функциями
$image = imagecreatefromjpeg($file); // создает изображение из jpg
} elseif ( $ext['type'] == 'image/png' ){
$image = imagecreatefrompng($file); // создает изображение из png
imagepalettetotruecolor($image); // восстанавливает цвета
imagealphablending($image, false); // выключает режим сопряжения цветов
imagesavealpha($image, true); // сохраняет прозрачность
}
imagewebp($image, $uploads['basedir'] . '/' . $metadata['file'] . '.webp', 90); // сохраняет файл в webp
foreach ($metadata['sizes'] as $size) { // перебирает все размеры файла и также сохраняет в webp
$file = $uploads['url'] . '/' . $size['file'];
$ext = $size['mime-type'];
if ( $ext == 'image/jpeg' ) {
$image = imagecreatefromjpeg($file);
} elseif ( $ext == 'image/png' ){
$image = imagecreatefrompng($file);
imagepalettetotruecolor($image);
imagealphablending($image, false);
imagesavealpha($image, true);
}
imagewebp($image, $uploads['basedir'] . $uploads['subdir'] . '/' . $size['file'] . '.webp', 90);
}
return $metadata;
}
add_filter('wp_generate_attachment_metadata', 'gt_webp_generation');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment