Skip to content

Instantly share code, notes, and snippets.

@zzap
Last active November 27, 2024 10:28
Show Gist options
  • Save zzap/8c673f6cc8bb10ca3bed82ac426dedd1 to your computer and use it in GitHub Desktop.
Save zzap/8c673f6cc8bb10ca3bed82ac426dedd1 to your computer and use it in GitHub Desktop.
Add image size to image src so that proper cropped image is served instead of original.
<?php
/**
* Add image size to image src so that proper cropped image is served instead of original.
*
* This is a very specific situation where the image tag has correct size attributes
* but, for some reason, the original source was used instead of cropped one.
* The code for serving image was in parent theme so editing that was not possible.
*/
$tags = new WP_HTML_Tag_Processor( $content );
while ( $tags->next_tag() ) {
if ( 'IMG' === $tags->get_tag() && '360' === $tags->get_attribute( 'width' ) ) {
$src = $tags->get_attribute( 'src' );
// Get parts of src separated by '.'
$end = explode( '.', $src );
// Get the last part - should be jpg, png, jpeg.
$end = end( $end );
// Get the image url up until last '.'
$url = substr( $src, 0, strrpos( $src, '.' ) );
// Insert the size part in between.
$proper_url = $url . '-360x360.' . $end;
// Set the proper crop URL as src attribute.
$tags->set_attribute( 'src', $proper_url );
}
}
return $tags->get_updated_html();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment