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:




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?


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'] === '') 
    // Replace src paths
    add_filter('wp_get_attachment_url', function ($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) 
                $source['url'] = str_replace(WP_HOME, 'https://www.some-production-site.com', $source['url']);
        return $sources;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.