Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.