調整wordpress,文章上傳圖片自動轉成Webp

目前Webp愈來愈多人使用,尤其是使用wordpress的人,因為wordpress外掛的關係,webp在快取方面有著非常優秀的優化,而轉webp的外掛也非常的多像是ImagifyConverter for Media都能輔助適用者將圖片自動轉成,但是有數量上的限制,不花錢的話有蠻多限制的,如果單純只是圖片轉成webp其實用PHP 或者JS就能做到,但我發現網路大多是webp第一代的也就是2010年google剛發布的版本,webp2(libwebp2)是Google自2021年6月起開發的新一代WebP,在SEO優化上使用webp2才會有明顯的效果

目前使用PHP 轉WEBP

function convert_image_to_webp($file){
    $info = pathinfo($file['file']);
    $new_file_path = $info['dirname'].'/'.$info['filename'].'.webp';

    switch ($file['type']) {
        case 'image/jpeg':
            $original_image = imagecreatefromjpeg($file['file']);
            break;
        case 'image/png':
            $original_image = imagecreatefrompng($file['file']);
            break;
        default:
            return $file;
    }

    imagewebp($original_image, $new_file_path, 80);
    imagedestroy($original_image);
    
    $file['file'] = $new_file_path;
    $file['url'] = str_replace($info['basename'], $info['filename'].'.webp', $file['url']);
    $file['type'] = 'image/webp';

    return $file;
}
add_filter('wp_handle_upload', 'convert_image_to_webp');


如果使用者是上傳JPG或PNG會自動轉換成WEBP,而且會配合wordpress的RWD設定,會自動生成尺寸大小不同的webp。



發表迴響