Skip to content

Instantly share code, notes, and snippets.

@seezee
Last active November 25, 2022 22:28
Show Gist options
  • Save seezee/e0b5f8fd4afa7229a518b2b13d0f17db to your computer and use it in GitHub Desktop.
Save seezee/e0b5f8fd4afa7229a518b2b13d0f17db to your computer and use it in GitHub Desktop.
WEBP for WordPress
<?php
/**
* Support for WEBP.
*
* @package myplugin
*/
// Security.
if ( ! defined( 'ABSPATH' ) ) {
die( 'Sorry, you are not allowed to access this page directly.' );
}
$webp = null;
// Is the header set?
if ( isset( $_SERVER['HTTP_ACCEPT'] ) ) {
// Sanitize the string.
$header = filter_input( INPUT_SERVER, 'HTTP_ACCEPT', FILTER_SANITIZE_STRING );
// Does the browser support WEBP?
if ( strpos( $header, 'image/webp' ) !== false ) {
$webp = true;
};
}
/**
* Filter the content for image files
*
* @param string $content The filtered conetent.
*/
function my_plugin_filter_webp( $content ) {
global $webp;
if ( ! is_admin() && is_singular() && is_main_query() && true === $webp ) {
$document = new DOMDocument();
libxml_use_internal_errors( true );
// Ensure UTF-8 is respected by using 'mb_convert_encoding'.
$document->loadHTML( mb_convert_encoding( $content, 'HTML-ENTITIES', 'UTF-8' ) );
// Find all of the images.
$tags = $document->getElementsByTagName( 'img' );
// Loop through the tags & get the attributes.
foreach ( $tags as $tag ) {
$src = $tag->getAttribute( 'src' );
$srcset = $tag->getAttribute( 'srcset' );
// Replace the suffixes.
$tag->setAttribute( 'src', str_replace( array( '.jpg', '.jpeg', '.png', '.gif' ), '.webp', $tag->getAttribute( 'src' ) ) );
$tag->setAttribute( 'srcset', str_replace( array( '.jpg', '.jpeg', '.png', '.gif' ), '.webp', $tag->getAttribute( 'srcset' ) ) );
}
return $document->saveHTML();
}
return $content;
}
add_filter( 'the_content', 'my_plugin_filter_webp' );
/**
* Change the image attributes
*
* @param string $attr The image attributes.
*/
function my_plugin_filter_attachment_webp( $attr ) {
global $webp;
if ( ! is_singular( array( 'post', 'page' ) ) || ( true !== $webp ) || ( is_admin() ) ) {
return $attr;
} else {
$attr['src'] = str_replace( array( '.jpg', '.jpeg', '.png', '.gif' ), '.webp', $attr['src'] );
$attr['srcset'] = str_replace( array( '.jpg', '.jpeg', '.png', '.gif' ), '.webp', $attr['srcset'] );
return $attr;
}
}
add_filter( 'wp_get_attachment_image_attributes', 'my_plugin_filter_attachment_webp', 10, 1 );
@seezee
Copy link
Author

seezee commented May 31, 2021

31 May 2021:

  • Fixed syntax errors
  • Removed broken & unnecessary function
  • Added check to see if browser header is set & sanitize it before using if it is
  • Cleaned up code to pass PHPCS checks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment