December 7, 2023

Convert Images to WebP in WordPress using Code Snippets

Play Video

This tutorial shows you how to efficiently Convert Images to WebP in WordPress using Code Snippets, improving your website’s speed and user experience.


Prerequisites

Please make sure you have the following installed and activated:


Additional knowledge

WebP is a modern image format that provides superior lossless and lossy compression for web images. It allows webmasters to create smaller, richer images, making the web faster. WordPress does not natively support WebP conversion, so utilizing a code snippet can automate this process.


Instructions to Convert Images to WebP in WordPress using Code Snippets

  1. Navigate to Snippets > Add New in your dashboard.
  2. Name the snippet and copy the provided code snippet for WebP conversion below:
    /**
     * Convert Uploaded Images to WebP Format
     *
     * This snippet converts uploaded images (JPEG, PNG, GIF) to WebP format
     * automatically in WordPress. Ideal for use in a theme's functions.php file,
     * or with plugins like Code Snippets or WPCodeBox.
     * 
     * @package    WordPress_Custom_Functions
     * @author     Mark Harris
     * @link       www.christchurchwebsolutions.co.uk
     *
     * Usage Instructions:
     * - Add this snippet to your theme's functions.php file, or add it as a new
     *   snippet in Code Snippets or WPCodeBox.
     * - The snippet hooks into WordPress's image upload process and converts
     *   uploaded images to the WebP format.
     *
     * Optional Configuration:
     * - By default, the original image file is deleted after conversion to WebP.
     *   If you prefer to keep the original image file, simply comment out or remove
     *   the line '@unlink( $file_path );' in the wpturbo_handle_upload_convert_to_webp function.
     *   This will preserve the original uploaded image file alongside the WebP version.
     */
    
    add_filter( 'wp_handle_upload', 'wpturbo_handle_upload_convert_to_webp' );
    
    function wpturbo_handle_upload_convert_to_webp( $upload ) {
        if ( $upload['type'] == 'image/jpeg' || $upload['type'] == 'image/png' || $upload['type'] == 'image/gif' ) {
            $file_path = $upload['file'];
    
            // Check if ImageMagick or GD is available
            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'];
    
                    // Create a new file path for the WebP image
                    $new_file_path = $dirname . '/' . $filename . '.webp';
    
                    // Attempt to save the image in WebP format
                    $saved_image = $image_editor->save( $new_file_path, 'image/webp' );
                    if ( ! is_wp_error( $saved_image ) && file_exists( $saved_image['path'] ) ) {
                        // Success: replace the uploaded image with 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 remove the original image
                        @unlink( $file_path );
                    }
                }
            }
        }
    
        return $upload;
    }

    Source: Code Snippet Cloud / Mark Harris

    Name the snippet and copy the provided code snippet for WebP conversion below

  3. Save changes and activate the snippet to enable its functionality.

    Note: Check Server Compatibility to ensure your server supports GD or ImageMagick.

  4. Upload images (PNG or JPEG) to your media library to auto-convert them to WebP.

Official Documentation


Convert Images to WebP in WordPress – Conclusion

This guide simplifies the process of converting images to WebP format in WordPress. By following these steps, you can significantly improve your website’s loading times and overall performance.

Required Resources

Code Snippets Logo
Free Options
Credit to Web Squadron
Web Squadron is a popular YouTube channel dedicated to providing informative tutorials, tips, and insights on web development and design. With a strong focus on WordPress and website builders like Bricks Builder, the channel aims to help users of all skill levels, from beginners to advanced developers, create and optimize their websites. By offering easy-to-understand, step-by-step guidance, Web Squadron provides practical and valuable content.
Visit
Convert Images to WebP in WordPress using Code Snippets
Welcome back!
Enter your Helwp credentials to sign in.

No Account yet? Sign Up

My Account
Menu
Give Feedback
Describe your feedback *
Rate Helwp
Share
Facebook
Twitter
LinkedIn
Reddit
Email
WhatsApp
Telegram
Pocket
Report
Problem *
Describe the problem
Want us to reply?
Your E-Mail
Affiliate Disclosure

At Helwp, we’re committed to transparency and honesty. Therefore, we want to inform you that some of the links on our website are affiliate links. This means that, at no additional cost to you, we may earn a small commission if you click through and make a purchase.

We only promote products or services that we genuinely believe in. These affiliate commissions help us to maintain the website and continue to provide you with free, high-quality WordPress content.

If you are interested in how you can support us even further, check out our support page.