Skip to content

Instantly share code, notes, and snippets.

@westonruter
Last active August 14, 2024 23:49
Show Gist options
  • Save westonruter/529210429bc8aa154cbb86685a459447 to your computer and use it in GitHub Desktop.
Save westonruter/529210429bc8aa154cbb86685a459447 to your computer and use it in GitHub Desktop.
<?php
/**
* Plugin Name: Auto-Sizes via HTML Tag Processor
*/
function auto_sizes_update_content_img_tag_with_html_tag_processor( $html ): string {
if ( ! is_string( $html ) ) {
$html = '';
}
$processor = new WP_HTML_Tag_Processor( $html );
// Bail if there is no IMG tag.
if ( ! $processor->next_tag( array( 'tag_name' => 'IMG' ) ) ) {
return $html;
}
// Bail early if the image is not lazy-loaded.
if ( 'lazy' !== $processor->get_attribute( 'loading' ) ) {
return $html;
}
$sizes = $processor->get_attribute( 'sizes' );
// Bail early if the image is not responsive.
if ( ! is_string( $sizes ) ) {
return $html;
}
// Don't add 'auto' to the sizes attribute if it already exists.
if ( auto_sizes_attribute_includes_valid_auto( $sizes ) ) {
return $html;
}
$processor->set_attribute( 'sizes', "AUTO, $sizes" ); // Upper-case AUTO just to make it clear when this version is running.
return $processor->get_updated_html();
}
add_action(
'plugins_loaded',
static function () {
remove_filter( 'wp_content_img_tag', 'auto_sizes_update_content_img_tag' );
if ( isset( $_GET['auto_sizes_via_html_tag_processor_disabled'] ) ) {
$function = 'auto_sizes_update_content_img_tag';
} else {
$function = 'auto_sizes_update_content_img_tag_with_html_tag_processor';
}
// TODO: benchmark-server-timing doesn't seem to be computing the median correctly here. I'm seeing it output identical values across the columns for multiple URLs passed via -f.
//if ( function_exists( 'perflab_wrap_server_timing' ) ) {
// $function = perflab_wrap_server_timing( $function, 'auto_sizes_update_content_img_tag', 'exist' );
//}
add_filter( 'wp_content_img_tag', $function );
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment