Skip to content

Instantly share code, notes, and snippets.

@rmpel
Created October 30, 2021 07:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmpel/af8af2255835086d5d32d1f0e95f9517 to your computer and use it in GitHub Desktop.
Save rmpel/af8af2255835086d5d32d1f0e95f9517 to your computer and use it in GitHub Desktop.
backfill missing wordpress uploads from a live website to a development copy
<?php
// Backfill missing uploads
// build your dev copy using plugins, theme and database
// don't download all uploads
// access an image on it, for example /wp-content/uploads/2021/10/some-image.png
// (of course, just loading a page with images on it will do)
// you will get 404s on all images
// place this file in mu-plugins folder
// try to access the url/page again
// this will download all missing images from the configured remote
// and redirect the image urls to load and show them
add_action('pre_handle_404', function() {
$backfill_remote_base = 'https://YOUR-SOURCE-WEBSITE-DOMAIN-HERE.com'; // <------------- this is the source domain
$path = wp_upload_dir()['basedir'];
$url = wp_upload_dir()['baseurl'];
$rel_url = parse_url($url, PHP_URL_PATH);
$remote_url = trim($backfill_remote_base, '/') . $rel_url;
if ( 0 === strpos($_SERVER['REQUEST_URI'], $rel_url) ) { // only handle uploads folder
$_SERVER['REQUEST_URI'] = rtrim($_SERVER['REQUEST_URI'], '/'); // remove the WordPress-added trailing slash
$file = str_replace($rel_url, $path, $_SERVER['REQUEST_URI']);
$dirs = str_replace($rel_url, '', dirname($_SERVER['REQUEST_URI']));
if (!is_file($file)) {
// create directories, if not exist
$dirs = explode('/', trim($dirs, './'));
$make_dir = $path;
foreach ($dirs as $dir) {
$make_dir = $make_dir .'/'. $dir;
if (!is_dir($make_dir)) {
mkdir($make_dir);
}
}
$local_full_url = remove_query_arg('');
$remote_full_url = trim($backfill_remote_base, '/') . $local_full_url;
$result = wp_remote_get( $remote_full_url, ['sslverify' => false ] ); // my local install has SSL issues
$file_data = wp_remote_retrieve_body( $result );
file_put_contents($make_dir .'/'. basename($file), $file_data );
$local_full_url = add_query_arg('_', microtime(true), $local_full_url);
wp_redirect($local_full_url, 307, basename(__FILE__));
exit;
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment