Blog, WordPress, WordPress Snippet Codes

Upload WebP Image Format on WordPress

WebP Image Format is one of the formats for pictures that it has lower size than the others. But some old browsers don’t support it.

WordPress by default does not support WebP image format. To force WordPress to upload this format, you need to add the function below to the functions.php file.

if (!function_exists('hs_webp_upload_mimes')) {
     function hs_webp_upload_mimes($existing_mimes)
     {
          $existing_mimes['webp'] = 'image/webp';
          return $existing_mimes;
     }
     add_filter('mime_types', 'hs_webp_upload_mimes');
}

After adding the above code to functions.php, WordPress will accept WebP format to upload but does not will display images in the Media section.

To display the WebP image format in the Media section, we must add the function below in functions.php.

if (!function_exists('hs_webp_is_displayable')) {
     function hs_webp_is_displayable($result, $path)
     {
          if ($result === false) {
               $displayable_image_types = array(IMAGETYPE_WEBP);
               $info = @getimagesize($path);
               if (empty($info)) {
                    $result = false;
               } elseif (!in_array($info[2], $displayable_image_types)) {
                    $result = false;
               } else {
                    $result = true;
               }
          }
          return $result;
     }
     add_filter('file_is_displayable_image', 'hs_webp_is_displayable', 10, 2);
}

Now you can upload WebP images and see them in Media section.

To convert image with other format to WebP, use this tool.