Last active
November 25, 2022 22:28
-
-
Save seezee/e0b5f8fd4afa7229a518b2b13d0f17db to your computer and use it in GitHub Desktop.
WEBP for WordPress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
31 May 2021: