Media PHP Intermediate

Serve Media Files From a CDN Domain

Rewrite image and file URLs from your uploads folder to a CDN or media subdomain, such as cdn.example.com.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 23 lines
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 );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

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.

How it works

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.

Things to watch

  • Set up the CDN first, with your site as the origin, and check a file loads from the CDN address.
  • Change https://cdn.example.com to your CDN hostname.
  • If you use a caching or CDN plugin that rewrites URLs, use its setting instead.

How to test it

View a page with images and inspect one. Its src and srcset should use your CDN domain.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only