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.
Opens WPIDE on
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
- 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.