-
-
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.
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 | |
/** | |
* 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