Serve webp and JPEG 2000 in wordpress

Last time we saw different methods to serve webp or JPEG 2000 pictures to our users. Now let’s see how we can implement this in wordpress

We might work something out thanks to our previous work on changing the wrapping of thumbnails: https://blog.seobytes.eu/wordpress/theme-customization/modify-thumbnails-wrapping-in-woocommerce-product-loop/

We shall also do the same operation on any other images be it post, product pages, background images, header images etc…

But let’s start with the thumbnails: the following code assume that our webp version of the images are in the same folder and have the same name than the jpg version, beside the extension.

remove_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10);
add_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10);

if ( ! function_exists( 'woocommerce_template_loop_product_thumbnail' ) ) {
function woocommerce_template_loop_product_thumbnail() {
echo woocommerce_get_product_thumbnail();
} 
}
if ( ! function_exists( 'woocommerce_get_product_thumbnail' ) ) { 
function woocommerce_get_product_thumbnail( $size = 'shop_catalog', $placeholder_width = 0, $placeholder_height = 0 ) {
global $post, $woocommerce;
$output = '</div class="imagewrapper"></picture>'; if ( has_post_thumbnail() ) { 
$image_url = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), $size);
$image_url =$image_url[0];
$webp_url= str_replace('jpg', 'webp', $image_url);
$output .= '<source srcset="'.$webp_url.'">';
$output .='<img class="lozad" data-src="'.$image_url.'" alt="">';
} 
$output .= '</picture ></div>';
return $output;
}
} 

With further research and the sudden realization that there might be a plugin already doing this (although, where is the fun in that?) I found the following plugins:

Webp express which is a free plugin

and Optimus which comes with a fee as far as webp conversion and serving is concerned.

While testing Webp express, it occurs that my virtual hosting does not allow for automatic conversion*. So I have written an article on how to batch convert pictures into webp

The author of Webp Express also made a php script to serve webp to supporting browser with .htaccess redirect which is a pretty elegant solution. Check the github page of the project

*My web host implemented imagick on the server after I inquired about it :) . No need to batch convert but it seems Imagick does not handle files containing a space in their name.