0

any function can apply change all image URLs to CDN instead of modifying media.php in wp-includes folder ?

2
  • are you comfortable with wp-cli?
    – rudtek
    Commented Dec 22, 2021 at 5:40
  • If you're using an existing CDN service there are very high chances that there is a plugin available for integration with WordPress. This allows for automatically rewriting all the URLs to a respective CDN URL. What CDN are you using?
    – Kumar
    Commented Dec 22, 2021 at 8:28

2 Answers 2

0

I did this by using wp super cache. One thing that confused me was that you have to turn on the caching, even if all you want is the CDN rewriting.

I looked at a number of other CDN/rewriting plugins and nothing worked.

0

You can place this in your functions.php file:

add_filter('wp_get_attachment_url', 'replace_media_url');
function replace_media_url($url) {
    $custom_url = 'https://mybucket.nyc3.cdn.digitaloceanspaces.com';
    $path = 'uploads';// the path in the CDN
    
    // Check if the URL is a media URL
    if (strpos($url, 'wp-content/uploads') !== false) {
        // Replace the media URL with the custom URL
        $url = str_replace('wp-content/uploads', $path, $url);
        $url = str_replace(site_url(), $custom_url, $url);
    }
    return $url;
}

Every time your media is accessed, WordPress will return the CDN URL instead (even in the admin area).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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