functions.php dosyasında düzenleme yapman gerekir resim formatları farklı olabilir.
function convert_images_to_webp($image) {
if (is_array($image)) {
$image_path = $image['file'];
} else {
$image_path = $image;
}
$image_extension = pathinfo($image_path, PATHINFO_EXTENSION);
$webp_path = preg_replace('/\.(jpe?g|png|gif)$/i', '.webp', $image_path);
if (file_exists($webp_path)) {
return $webp_path;
}
if (imagewebp(imagecreatefromstring(file_get_contents($image_path)), $webp_path, 80)) {
return $webp_path;
}
return $image;
}
function display_webp_images($content) {
$pattern = '/<img(.*?)src=[\'"](.*?).(bmp|gif|ico|jpe?g|png)[\'"](.*?)>/i';
$replacement = '<img$1src="$2.$3" data-src-webp="$2.webp"$4>';
$content = preg_replace($pattern, $replacement, $content);
return $content;
}
function generate_webp_images() {
if (!function_exists('imagewebp')) {
return;
}
add_filter('wp_generate_attachment_metadata', function ($metadata, $attachment_id) {
$attachment = get_post($attachment_id);
$mime_type = get_post_mime_type($attachment_id);
if (strpos($mime_type, 'image') !== false) {
$file = get_attached_file($attachment_id);
$webp_file = convert_images_to_webp($file);
if (is_array($metadata) && isset($metadata['sizes'])) {
foreach ($metadata['sizes'] as $size => $size_info) {
$file = path_join(dirname($webp_file), $size_info['file']);
$metadata['sizes'][$size]['file'] = $file;
convert_images_to_webp($file);
}
}
}
return $metadata;
}, 10, 2);
add_filter('the_content', 'display_webp_images', 99);
add_filter('post_thumbnail_html', 'display_webp_images', 99);
add_filter('widget_text_content', 'display_webp_images', 99);
add_filter('wp_get_attachment_image_attributes', function ($attr) {
if (isset($attr['data-src-webp'])) {
$attr['src'] = $attr['data-src-webp'];
unset($attr['data-src-webp']);
}
return $attr;
});
}
generate_webp_images();
Hocam merhaba, ilgili kodu ekledim fakat dönüşmedi webp olarak ek bir işlem mi gerekiyor?