Halloween Sale 15% off Ends in See the plans
PHP

Load Missing Media From the Live Site on Local Copies

On local, development and staging copies, images and files that are not in the local uploads folder are loaded from the live site instead, so you do not need to download gigabytes of uploads.

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

Code

// Production site address, without a trailing slash.
$wpide_live_url = 'https://www.example.com';

$wpide_live_media = function ( $url ) use ( $wpide_live_url ) {
    static $uploads = null;

    if ( 'production' === wp_get_environment_type() || ! is_string( $url ) || '' === $url ) {
        return $url;
    }
    if ( null === $uploads ) {
        $uploads = wp_get_upload_dir();
    }
    if ( 0 !== strpos( $url, $uploads['baseurl'] ) ) {
        return $url;
    }

    $relative = substr( $url, strlen( $uploads['baseurl'] ) );
    $local    = $uploads['basedir'] . strtok( $relative, '?' );
    if ( file_exists( $local ) ) {
        return $url;
    }

    $live_base = untrailingslashit( $wpide_live_url ) . wp_parse_url( $uploads['baseurl'], PHP_URL_PATH );
    return $live_base . $relative;
};

add_filter( 'wp_get_attachment_url', $wpide_live_media );

add_filter( 'wp_calculate_image_srcset', function ( $sources ) use ( $wpide_live_media ) {
    foreach ( (array) $sources as $width => $source ) {
        $sources[ $width ]['url'] = $wpide_live_media( $source['url'] );
    }
    return $sources;
} );

add_filter( 'the_content', function ( $content ) use ( $wpide_live_media ) {
    if ( 'production' === wp_get_environment_type() || false === strpos( $content, '/uploads/' ) ) {
        return $content;
    }
    return preg_replace_callback( '#(?<=["\'\s(])https?://[^"\'\s)]+/uploads/[^"\'\s)]+#i', function ( $match ) use ( $wpide_live_media ) {
        return $wpide_live_media( $match[0] );
    }, $content );
}, 99 );

Notes

Set $wpide_live_url to your production address; it never runs on production and only rewrites URLs whose file is missing locally.

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.