[WordPress] 媒體庫支援上傳、預覽 WebP 格式圖檔

本篇文章更新時間:2021/10/28
如有資訊過時或語誤之處,歡迎使用 Contact 功能通知。
一介資男的 LINE 社群開站囉!歡迎入群聊聊~
如果本站內容對你有幫助,歡迎使用 BFX Pay 加密貨幣新台幣 贊助支持。


這個需求不是「把媒體庫圖片轉成 WebP 格式」,或是「讓網站提供 WebP 格式的媒體輸出」。就是很單純的讓媒體庫可以上傳 WebP 格式的圖檔,並且可以預覽這圖檔。

內建預設沒開放直接上傳這格式的情況下,會需要一點 hack 方式,或是安裝外掛來辦到。

關於 WordPress 打算內建支援 WebP 格式的新聞可以參考: WordPress 5.8 adds WebP support

外掛是:Allow Webp image 安裝啟用就有效果。

不過如果覺得外掛實在有點多餘,可以補上兩個 hook 搞定(外掛裡面其實也是重點這兩個 hook)

function mxp_webp_upload_mimes($existing_mimes) {
    // add webp to the list of mime types
    $existing_mimes['webp'] = 'image/webp';

    // return the array back to the function with our added mime type
    return $existing_mimes;
}
add_filter('mime_types', 'mxp_webp_upload_mimes');

//** * Enable preview / thumbnail for webp image files.*/
function mxp_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', 'mxp_webp_is_displayable', 10, 2);

補在子主題下的 functions.php 就有效果,也能節省一點主機的 IO 效能。


Share:

作者: Chun

資訊愛好人士。主張「人人都該為了偷懶而進步」。期許自己成為斜槓到變進度條 100% 的年輕人。[///////////____36%_________]

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *


文章
Filter
Mastodon