iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
💨

Enable WebP in WordPress without plugins in about 20 lines of code

に公開
2021/05/04

With the latest Safari now supporting WebP, it really feels like the year WebP goes mainstream. This is a method I used to implement WebP on a personally managed WordPress site without relying on plugins.

Conclusion First

For those who just want the results, add the following to each file and upload your images with the naming convention hoge.jpg and hoge.jpg.webp.

▼functions.php

/**
 * Allow Webp
 */
function custom_mime_types( $mimes ) {
  $mimes['webp'] = 'image/webp';
  return $mimes;
}
add_filter( 'upload_mimes', 'custom_mime_types' );

/**
 * Do not add _scaled to large images
 */
add_filter("big_image_size_threshold", "__return_false");

▼htaccess

<IfModule mod_rewrite.c>
  # Enable Rewrite Engine
  RewriteEngine On

  # Apply subsequent RewriteRules only if the Accept request header sent from the browser contains image/webp
  RewriteCond %{HTTP_ACCEPT} image/webp

  # Apply subsequent RewriteRules only if a WebP version of the file exists
  # Using SCRIPT_FILENAME eliminates the need for subdirectory completion
  RewriteCond %{SCRIPT_FILENAME}.webp -f

  # Internally route *.jpg and *.png files to *.webp files
  # Set Content-Type to image/webp
  RewriteRule .(jpe?g|png)$ %{REQUEST_URI}.webp [T=image/webp,E=accept:1]
</IfModule>

<IfModule mod_headers.c>
  # If the environment variable _image_request is true (set by SetEnvIf above),
  # add Accept to the Vary response header
  Header append Vary Accept env=_image_request
</IfModule>

<IfModule mod_mime.c>
  # Return image/webp as Content-Type for .webp extensions
  AddType image/webp .webp
</IfModule>

Detailed Explanation

In enabling WebP for WordPress, I am performing two main tasks:

  • Permitting WebP file uploads
  • Serving WebP to compatible environments while falling back to JPG for incompatible ones
    Regarding the fallback, since older versions of Safari, IE11, and some crawlers like those for OGP may not support it, it is better to include fallback processing.

As for image management, I prepare an image named hoge.jpg.webp for hoge.jpg. The reason I don't use hoge.webp is due to the requirements of the redirection logic in .htaccess.

Permitting WebP Uploads

By default, WordPress does not allow WebP uploads, so add the following to your theme's functions.php to permit them:

/**
 * Allow Webp
 */
function custom_mime_types( $mimes ) {
  $mimes['webp'] = 'image/webp';
  return $mimes;
}
add_filter( 'upload_mimes', 'custom_mime_types' );

There was information suggesting that adding the following to wp-config.php would work:

define( 'ALLOW_UNFILTERED_UPLOADS', true ); // This did not work in WordPress 5.7...

However, this did not work in WordPress 5.7. Additionally, add this to functions.php:

/**
 * Do not add _scaled to large images
 */
add_filter("big_image_size_threshold", "__return_false");

This prevents WordPress from appending a -scaled.jpg suffix to filenames when uploading large images (2560px or larger), a behavior introduced in WordPress 5.3. If the suffix is added, the naming convention mentioned above will break. If you do not use large images, this is not strictly necessary.

Delivery Switching via .htaccess

Based on the browser's header information, we add a process to return a file named hoge.jpg.webp in response to a request for hoge.jpg for WebP-compatible browsers. For more details, please refer to .htaccess-based Selective WebP Response: Problems and Improvements - Qiita, which I used as a reference.

In my environment, the WordPress files were not placed directly in the domain root but in a folder like wordpress, so I modified the code slightly.

Using WebP in WordPress

When creating a post in WordPress, use the hoge.jpg file. Although it is output as hoge.jpg in the HTML, the file sent via server-side processing will be hoge.jpg.webp. It is successful if the Type of hoge.jpg in the Network tab of the developer tools is webp.

With this, you can support high-quality, low-capacity WebP files in WordPress without using a plugin.

Optional: Disable Image Size Switching via Art Direction

This is an optional setting. When inserting images from WordPress posts, there is an art direction feature that switches image sizes according to the display width. (This is not a WP-specific feature, but a switch based on the HTML srcset attribute.) If the display size is small, a resized image is displayed. Since only the original size image is prepared as WebP, it would be delivered as a JPG.

To disable this srcset switching, add the following code to your functions.php.

add_filter( 'wp_calculate_image_srcset_meta', '__return_null' );

This disables the art direction feature and ensures only the specified image is used.

Bonus

If you find it tedious to convert images to WebP, I have created a tool that converts images in bulk with a single command.

https://github.com/ics-nishihara/simple-image-optimiser

Discussion