Posts

Auto JPG, PNG, Converter Code Into Webp

 /**

 * Convert Uploaded Images to WebP Format

 *

 * This snippet automatically converts JPEG, PNG, and GIF images 

 * to WebP format during the upload process.

 */


add_filter('wp_handle_upload', 'wpturbo_handle_upload_convert_to_webp');

function wpturbo_handle_upload_convert_to_webp($upload) {

    if (in_array($upload['type'], ['image/jpeg', 'image/png', 'image/gif'])) {

        $file_path = $upload['file'];

        if (extension_loaded('imagick') || extension_loaded('gd')) {

            $image_editor = wp_get_image_editor($file_path);

            if (!is_wp_error($image_editor)) {

                $file_info = pathinfo($file_path);

                $dirname = $file_info['dirname'];

                $filename = $file_info['filename'];

                $def_filename = wp_unique_filename($dirname, $filename . '.webp');

                $new_file_path = $dirname . '/' . $def_filename;

                $saved_image = $image_editor->save($new_file_path, 'image/webp');

                if (!is_wp_error($saved_image) && file_exists($saved_image['path'])) {

                    // Update the upload data to use the WebP image

                    $upload['file'] = $saved_image['path'];

                    $upload['url'] = str_replace(basename($upload['url']), basename($saved_image['path']), $upload['url']);

                    $upload['type'] = 'image/webp';


                    // Optionally delete the original file

                    @unlink($file_path);

                }

            }

        }

    }


    return $upload;

}

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.