Skip to content

Instantly share code, notes, and snippets.

@trey8611
Last active April 17, 2024 17:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trey8611/80de74881b7fab2f1de1c4decd9a7729 to your computer and use it in GitHub Desktop.
Save trey8611/80de74881b7fab2f1de1c4decd9a7729 to your computer and use it in GitHub Desktop.
Remove image sizes from image URLs in content

Remove -000x000.ext from image URLs in content by passing the content to a custom PHP function:

[my_fix_images({content[1]})]

Code (save in the Function Editor at All Import › Settings):

function my_fix_img( $img = '' ) {
	if ( empty( $img ) ) return false;
	$img_regex = preg_match( '/(. *\d)(x)(\d. *)./', $img, $match );
	
	if ( $img_regex === 1 ) {
		$extension = pathinfo( $img, PATHINFO_EXTENSION );
		$img = explode( '-', $img );
		
		$img_remove = array_pop( $img );
		
		$img = implode( '-', $img ) . '.' . $extension;
		return $img;
	} else {
		return $img;
	}
}
function my_fix_images( $html ) {
    $doc = new DOMDocument();
    // In some cases, you may need to convert the encoding in the HTML:
    // @$doc->loadHTML( mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD );
    @$doc->loadHTML( $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD );
    $imageTags = $doc->getElementsByTagName( 'img' );
    $all_images = array();

    foreach( $imageTags as $tag ) {
        $img = $tag->getAttribute( 'src' );
		$img = my_fix_img( $img );
		$tag->setAttribute( 'src', $img );	
    }

    return $doc->saveHTML();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment