Change any image file format to ‘webp’ during media upload (with thumbnails in ‘webp’) and return the file path in the ‘webp’ format


I want to change the file format of any jpg/png/gif image uploaded (through media library / post featured image / gallery and wherever else applicable) to webp format (along with the thumbnails). Only the webp file will be stored after conversion and the media library should show the webp file only. Also the reference from where the upload has been invoked (ex. featured image/gallery) will use the webp file.

Till now I got the files converted, stored and returned as webp. They are also displayed properly in the media library. But the problems is:

  • Only the webp file is formed and returned against the original jpg/png/gif image file, but the thumbnails are not generated. Can’t I generate the thumbnails for webp?

Here is my code:

class PxNextGenMedia {

    public function __construct() {
        add_filter('mime_types', array($this, 'px73_nestgen_mimes'));
        add_filter('file_is_displayable_image', array($this, 'px73_display_nextgen'), 10, 2);
        add_filter('wp_handle_upload_prefilter', array($this, 'px73_convert_nextgen_img'));

    function px73_nestgen_mimes($existing_mimes) {
        $existing_mimes['webp'] = 'image/webp';
        return $existing_mimes;

    function px73_convert_nextgen_img($file) {
        $info = getimagesize($file['tmp_name']);
        if ($info !== FALSE) {
            $image = NULL;
            if (($info[2] === IMAGETYPE_GIF)) {
                $image = imagecreatefromgif($file['tmp_name']);
            } elseif ($info[2] === IMAGETYPE_JPEG) {
                $image = imagecreatefromjpeg($file['tmp_name']);
            } elseif ($info[2] === IMAGETYPE_PNG) {
                $image = imagecreatefrompng($file['tmp_name']);
            if ($image != NULL) {
                imagewebp($image, $file['tmp_name']);
                $file['name'] .= '.webp';
                $file['size'] = getimagesize($file['tmp_name']);
                $file['type'] = 'image/webp';
        return $file;

    function px73_display_nextgen($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;

What do I need to change/add to generate thumbnails for webp?

sariDon 4 months 0 Answers 25 views 0

Leave an answer