はじめに
プラグイン「EWWW Image Optimizer」などを使わずに、画像アップロード時にPHPのGDライブラリを用いてWebP形式へ自動変換します。
この記事では、この方法について説明します。
実装手順
以下のコードをfunctions.phpに追加します。
add_filter('wp_handle_upload', function ($upload) {
$file = $upload['file'];
$file_type = wp_check_filetype($file);
// JPEG・PNG以外は処理対象外
if (!in_array($file_type['type'], ['image/jpeg', 'image/png'], true)) {
return $upload;
}
// WordPressの画像エディタを取得
$editor = wp_get_image_editor($file);
if (is_wp_error($editor)) {
return $upload;
}
// WebPファイルのパスを作成
$webp_path = preg_replace('/\.(jpe?g|png)$/i', '.webp', $file);
// 画質80でWebPを保存
$editor->set_quality(80);
$saved = $editor->save($webp_path, 'image/webp');
if (!is_wp_error($saved)) {
// WebPへの変換成功後に元画像を削除
if (file_exists($file)) {
unlink($file);
}
$upload['file'] = $webp_path;
$upload['url'] = preg_replace('/\.(jpe?g|png)$/i', '.webp', $upload['url']);
$upload['type'] = 'image/webp';
}
return $upload;
});
さいごに
今回紹介した方法を使えば、プラグインを使わずに、画像をアップロードするたびに自動でWebP形式へ変換する処理を実現できます。
GDライブラリを利用することで、余計な機能や設定を追加せず、軽量でシンプルに運用できます。
