Rewrite image and file URLs from your uploads folder to a CDN or media subdomain, such as cdn.example.com.
function nahnu_cdn_url( string $url ): string {
$cdn = 'https://cdn.example.com';
$uploads = wp_get_upload_dir();
return str_replace( $uploads['baseurl'], untrailingslashit( $cdn ) . wp_parse_url( $uploads['baseurl'], PHP_URL_PATH ), $url );
}
add_filter( 'wp_get_attachment_url', function ( string $url ): string {
return is_admin() ? $url : nahnu_cdn_url( $url );
} );
add_filter( 'wp_calculate_image_srcset', function ( $sources ) {
if ( is_admin() || ! is_array( $sources ) ) {
return $sources;
}
foreach ( $sources as &$source ) {
$source['url'] = nahnu_cdn_url( $source['url'] );
}
return $sources;
} );
add_filter( 'the_content', function ( string $content ): string {
return nahnu_cdn_url( $content );
}, 99 );
Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.
A pull CDN like Bunny CDN or Cloudflare’s custom hostnames copies files from your site the first time they’re requested, then serves them from servers near your visitors. You just need your media URLs to point at the CDN domain.
The helper swaps your uploads base URL, like https://example.com/wp-content/uploads, for the same path on the CDN domain.
It runs on wp_get_attachment_url (the main file URL), wp_calculate_image_srcset (every responsive size) and the_content (URLs already saved in posts). wp-admin keeps your normal URLs, so editing isn’t affected.
https://cdn.example.com to your CDN hostname.View a page with images and inspect one. Its src and srcset should use your CDN domain.