Search code examples
phpwordpresswebp

Get webp image if browser supports it using get_the_post_thumbnail()


So I would like to implement webp to a website. Currently im using get_the_post_thumbnail() function to get the post featured image. Is there a way to get the webp version of the image using this function.

I have tried using the wp-webp plugin but it does not work.

Cheers


Solution

  • Ok the only way I can think of getting around this problem is to check the broswer and serve up a .webp image if the browser supports it by replacing the file extention with .webp

    $postId = $post->ID;
    $patterns = array("/.jpg/", "/.jpeg/", "/.png/");
    $thePostThumbUrl = get_the_post_thumbnail_url($postId, array(768,768));
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'Opera') || strpos($_SERVER['HTTP_USER_AGENT'], 'OPR/') || strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome') && !strpos($_SERVER['HTTP_USER_AGENT'], 'Edge')) 
        $thePostThumbUrl = preg_replace($patterns, ".webp", $thePostThumbUrl);