I recently needed to add .webp support to one of my websites so I used the following code:
<?php
/**
* Add WebP image support to WordPress uploads.
* This allows uploading .webp files and ensures they're recognized as images.
*/
// Hook into the upload_mimes filter to add WebP MIME type
function add_webp_upload_support( $mimes ) {
$mimes['webp'] = 'image/webp';
return $mimes;
}
add_filter( 'upload_mimes', 'add_webp_upload_support' );
/**
* Optional: Ensure WebP images are properly handled in the media library.
* This adds WebP to the list of allowed image types for the editor.
*/
function add_webp_to_image_send_to_editor( $html, $id, $attachment, $width, $height, $class, $align, $url, $caption ) {
if ( strpos( $attachment->post_mime_type, 'webp' ) !== false ) {
// WebP is already supported, but ensure it renders correctly.
return $html;
}
return $html;
}
add_filter( 'image_send_to_editor', 'add_webp_to_image_send_to_editor', 10, 9 );
?>
How to Use:
- Open your active theme’s functions.php file (via Appearance > Theme Editor in WordPress admin, or FTP).
- Paste the code at the end of the file, before the closing ?> if present.
- Save the file. You can now upload .webp images via the Media Library.
This enables basic WebP support for uploads and display. For automatic conversion from other formats to WebP (for better performance), consider a plugin like “WebP Express” or extend this code with image processing libraries like Imagick if your server supports it. Test thoroughly to avoid breaking your site!