S_R
S_R

Reputation: 1998

Wordpress webp image previews

I have updated wordpress using the following code to allow for webp uploads,

function webp_upload_mimes( $existing_mimes ) {
    $existing_mimes['webp'] = 'image/webp';
    return $existing_mimes;
}
add_filter( 'mime_types', 'webp_upload_mimes' );

Which works great, but the webp images do not show a preview in the media selector, as shown

enter image description here

Is there anyway I can force wordpress to render webp previews? By the time my site is done, it could potentially have hundreds of webp images, not being able to see them when selecting could be a huge pain!

Upvotes: 6

Views: 4084

Answers (3)

Sebastian Brosch
Sebastian Brosch

Reputation: 43574

Update July 2021

From WordPress version 5.8 forward, you can upload and use WebP images in WordPress like you would a JPEG or PNG image today (as long as your hosting service supports WebP). Switching to the WebP format for your images will improve your site’s performance and your site visitor’s experience.
https://make.wordpress.org/core/2021/06/07/wordpress-5-8-adds-webp-support/


I found a solution to show the thumbnails on the media manager. You have to add the following code to the functions.php of your active theme:

//enable upload for webp image files.
function webp_upload_mimes($existing_mimes) {
    $existing_mimes['webp'] = 'image/webp';
    return $existing_mimes;
}
add_filter('mime_types', 'webp_upload_mimes');

//enable preview / thumbnail for webp image files.
function 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', 'webp_is_displayable', 10, 2);

The webp_is_displayable function is using the file_is_displayable_image hook and checks if the file (on $path) is a webp image file. To check for the webp image file the function is using the constant IMAGETYPE_WEBP.

Upvotes: 9

Grégory Brancq
Grégory Brancq

Reputation: 11

The solution proposed by Sebastian Brosch is still working. But as S_R commented, the old webp images won't have a working preview. For that, you can use the wordpress plugin "Force Regenerate Thumbnails" to reload old images and create previews.

Upvotes: 1

Benyamin Amiri
Benyamin Amiri

Reputation: 11

One more thing, if you want WordPress to allow you to upload webp to the media/library you can use this code:

//** Enable upload for webp image files.
function webp_upload_mimes($existing_mimes) {
    $existing_mimes['webp'] = 'image/webp';
    return $existing_mimes;
}
add_filter('mime_types', 'webp_upload_mimes');

Upvotes: 0

Related Questions