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;
}
);
}