Redirect Missing Resized Images to the Original
Sends requests for resized images that no longer exist, such as photo-300x200.jpg after a theme change, to the original upload, fixing broken images in old posts and on other sites.
Opens WPIDE on
Code
add_action( 'template_redirect', function () {
if ( ! is_404() ) {
return;
}
$path = isset( $_SERVER['REQUEST_URI'] ) ? rawurldecode( (string) wp_parse_url( wp_unslash( $_SERVER['REQUEST_URI'] ), PHP_URL_PATH ) ) : '';
$uploads = wp_get_upload_dir();
$base = (string) wp_parse_url( $uploads['baseurl'], PHP_URL_PATH );
// Only resized copies such as photo-300x200.jpg inside the uploads folder.
if ( '' === $path || 0 !== strpos( $path, trailingslashit( $base ) ) || ! preg_match( '/^(.+)-\d+x\d+(\.(?:jpe?g|png|gif|webp|avif))$/i', $path, $m ) ) {
return;
}
$relative = substr( $m[1], strlen( $base ) );
if ( false !== strpos( $relative, '..' ) ) {
return;
}
// Large uploads keep their original as name-scaled.jpg; check that first.
foreach ( array( '-scaled', '' ) as $suffix ) {
$file = $relative . $suffix . $m[2];
if ( file_exists( $uploads['basedir'] . $file ) ) {
wp_safe_redirect( $uploads['baseurl'] . implode( '/', array_map( 'rawurlencode', explode( '/', $file ) ) ), 301 );
exit;
}
}
} );
Notes
Only works when your web server passes missing upload files to WordPress, as the default Apache setup does.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.