Skip to content

Instantly share code, notes, and snippets.

@vanpariyar
Last active December 26, 2022 11:15
Show Gist options
  • Save vanpariyar/291af4114a6c3669cde40d7397f07075 to your computer and use it in GitHub Desktop.
Save vanpariyar/291af4114a6c3669cde40d7397f07075 to your computer and use it in GitHub Desktop.
Use production image in local environment

How to use production image in the Local environment to fetch the path from the production

By doing This you can work on the local environment easily

const LOCAL_DOMAIN = "lcoalhost/project";
const LIVE_DOMAIN = "project_url";

// changes in the Url so we can store images in one place.
add_filter('wp_get_attachment_image_src', 'rewriteImgSrc', 10, 3);
function rewriteImgSrc($image, $attachment_id, $size ) {
    if($image) {
        $image[0] = str_replace( LOCAL_DOMAIN, LIVE_DOMAIN, $image[0]);
    }
    return $image;
}
add_filter('wp_get_attachment_image_src', 'rewriteImgSrc', 10, 3);             
if($_SERVER['REMOTE_ADDR'] === '127.0.0.1') {
// Replace src paths
	add_filter('wp_get_attachment_url', function ($url) { 
			if(file_exists($url)) {
			  return $url;
			}
			return str_replace( LOCAL_DOMAIN, LIVE_DOMAIN, $url);
		}
	);

	// Replace srcset paths
	add_filter('wp_calculate_image_srcset', function ($sources) {
			foreach($sources as &$source) 
			{
				if(!file_exists($source['url'])) {
					$source['url'] = str_replace(LOCAL_DOMAIN, LIVE_DOMAIN, $source['url']);
				}
			}
			return $sources;
		}
	);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment