Convert jpg, jpeg and png into wepb code for worpress
/**
* WebP Converter - Store in External Folder
*/
/**
* Convert single image to WebP (store in external folder)
*/
function convert_existing_image_to_webp($image_path) {
if (!function_exists('imagewebp')) {
return false;
}
$upload_dir = wp_upload_dir();
// 👉 Custom folder name
$webp_base_dir = $upload_dir['basedir'] . '/webp-images';
$webp_base_url = $upload_dir['baseurl'] . '/webp-images';
// Create base folder if not exists
if (!file_exists($webp_base_dir)) {
wp_mkdir_p($webp_base_dir);
}
$path_info = pathinfo($image_path);
// 👉 Preserve subfolder structure (e.g. /2024/01/)
$relative_path = str_replace($upload_dir['basedir'], '', $path_info['dirname']);
$target_dir = $webp_base_dir . $relative_path;
if (!file_exists($target_dir)) {
wp_mkdir_p($target_dir);
}
$webp_path = $target_dir . '/' . $path_info['filename'] . '.webp';
// If already exists
if (file_exists($webp_path)) {
return $webp_path;
}
$image_info = getimagesize($image_path);
if (!$image_info) {
return false;
}
$mime_type = $image_info['mime'];
switch ($mime_type) {
case 'image/jpeg':
$image = imagecreatefromjpeg($image_path);
break;
case 'image/png':
$image = imagecreatefrompng($image_path);
imagepalettetotruecolor($image);
imagealphablending($image, true);
imagesavealpha($image, true);
break;
default:
return false;
}
if (!$image) {
return false;
}
$result = imagewebp($image, $webp_path, 80);
imagedestroy($image);
return $result ? $webp_path : false;
}
/**
* Bulk convert all images
*/
function bulk_convert_images_to_webp() {
$args = array(
'post_type' => 'attachment',
'post_mime_type' => array('image/jpeg', 'image/jpg', 'image/png'),
'post_status' => 'inherit',
'posts_per_page' => -1,
);
$attachments = get_posts($args);
$converted = 0;
$failed = 0;
foreach ($attachments as $attachment) {
$file_path = get_attached_file($attachment->ID);
if (!file_exists($file_path)) {
continue;
}
$result = convert_existing_image_to_webp($file_path);
if ($result) {
$converted++;
// Convert thumbnails also
$metadata = wp_get_attachment_metadata($attachment->ID);
if (!empty($metadata['sizes'])) {
$base_dir = dirname($file_path);
foreach ($metadata['sizes'] as $size) {
$size_file = $base_dir . '/' . $size['file'];
if (file_exists($size_file)) {
convert_existing_image_to_webp($size_file);
}
}
}
} else {
$failed++;
}
}
return [
'total' => count($attachments),
'converted' => $converted,
'failed' => $failed
];
}
/**
* Admin Menu Page
*/
add_action('admin_menu', function () {
add_management_page(
'WebP Converter',
'Convert to WebP',
'manage_options',
'webp-converter',
'webp_converter_page'
);
});
function webp_converter_page() {
?>
<div class="wrap">
<h1>Convert Images to WebP (External Folder)</h1>
<?php
if (isset($_POST['convert_images']) && check_admin_referer('webp_convert_action')) {
$results = bulk_convert_images_to_webp();
?>
<div class="notice notice-success">
<p>
<strong>Done!</strong><br>
Total: <?php echo $results['total']; ?><br>
Converted: <?php echo $results['converted']; ?><br>
Failed: <?php echo $results['failed']; ?>
</p>
</div>
<?php } ?>
<form method="post">
<?php wp_nonce_field('webp_convert_action'); ?>
<p>This will convert all images and store WebP in <strong>/uploads/webp-images/</strong></p>
<input type="submit" name="convert_images" class="button button-primary" value="Convert Now">
</form>
</div>
<?php
}
/**
* Auto convert on upload
*/
add_filter('wp_handle_upload', function ($upload) {
if (in_array($upload['type'], ['image/jpeg', 'image/png', 'image/jpg'])) {
convert_existing_image_to_webp($upload['file']);
}
return $upload;
});
/**
* Serve WebP instead of original
*/
add_filter('wp_get_attachment_url', function ($url, $attachment_id) {
if (!isset($_SERVER['HTTP_ACCEPT']) || strpos($_SERVER['HTTP_ACCEPT'], 'image/webp') === false) {
return $url;
}
$upload_dir = wp_upload_dir();
$file_path = get_attached_file($attachment_id);
$path_info = pathinfo($file_path);
$relative_path = str_replace($upload_dir['basedir'], '', $path_info['dirname']);
$webp_path = $upload_dir['basedir'] . '/webp-images' . $relative_path . '/' . $path_info['filename'] . '.webp';
if (file_exists($webp_path)) {
return $upload_dir['baseurl'] . '/webp-images' . $relative_path . '/' . $path_info['filename'] . '.webp';
}
return $url;
}, 10, 2);
/**
* WP CLI Support
*/
if (defined('WP_CLI') && WP_CLI) {
WP_CLI::add_command('images convert-webp', function () {
WP_CLI::line('Converting images...');
$results = bulk_convert_images_to_webp();
WP_CLI::success("Done! Total: {$results['total']}, Converted: {$results['converted']}, Failed: {$results['failed']}");
});
}