Change WordPress image URLs via filter

I’m planning to create a wordpress plugin that will offload uploaded images to external website and show them from there.

What I did so far:

1) Whenever a images gets uploaded, my custom functions will trigger and will upload the image including its thumbnails to the external site and store the urls to database.

No problems here. But how do I tell wordpress instead of showing default image url show my url? I am just looking for the correct filter/hooks. I’m googling for past 12 hours still hasn’t found a proper answer.

What I want is, whenever requests a image the filter will change:

http://localhost/wordpress/wp-content/uploads/2019/03/dog-1200x1108.png

to

http://example.com/BAHIAPJGJSHSH.png

There are 2 plugins which does this: DigitalOcean Spaces Sync and WP Offload Media

This 2 plugin does this although I’m trying to do it in a different image hoster. I’ve tried looking out there source code, but could not figure out.

Can anyone please point me in the right direction?
How wordpress displays the image? and How to change the url via filter?

2 s
2

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