Change WordPress image URLs via filter

You will most likely want to use filters. The main issue is that developers will need to make sure to use the correct functions like “the_post_thumbnail()” etc.
You can use wp_get_attachment_url
https://codex.wordpress.org/Function_Reference/wp_get_attachment_url

I use this when doing local development, but want all my local images to load from the Production server as I don’t have any images on my local machine.

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(WP_HOME, 'https://www.some-production-site.com', $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(WP_HOME, 'https://www.some-production-site.com', $source['url']);
            }
        }
        return $sources;
    });
}

Leave a Comment