Serve Media and Static Files From a CDN Domain
Rewrites the URLs of your uploads, theme and plugin files to a CDN or pull-zone domain you set, so images, CSS and JavaScript are delivered from the CDN while pages are still served by your site.
Opens WPIDE on
Code
// Your CDN address, without a trailing slash.
$wpide_cdn_url = 'https://cdn.example.com';
// Folders whose files are served from the CDN.
$wpide_cdn_dirs = array( 'wp-content/uploads', 'wp-content/themes', 'wp-content/plugins', 'wp-includes' );
if ( 'https://cdn.example.com' !== $wpide_cdn_url ) {
$wpide_cdn_rewrite = function ( $url ) use ( $wpide_cdn_url, $wpide_cdn_dirs ) {
if ( ! is_string( $url ) || is_admin() || is_preview() || is_customize_preview() ) {
return $url;
}
$site = untrailingslashit( set_url_scheme( site_url(), 'https' ) );
foreach ( $wpide_cdn_dirs as $dir ) {
foreach ( array( $site, set_url_scheme( $site, 'http' ) ) as $origin ) {
if ( 0 === strpos( $url, $origin . '/' . $dir . '/' ) ) {
return untrailingslashit( $wpide_cdn_url ) . substr( $url, strlen( $origin ) );
}
}
}
return $url;
};
add_filter( 'wp_get_attachment_url', $wpide_cdn_rewrite, 99 );
add_filter( 'script_loader_src', $wpide_cdn_rewrite, 99 );
add_filter( 'style_loader_src', $wpide_cdn_rewrite, 99 );
add_filter( 'wp_calculate_image_srcset', function ( $sources ) use ( $wpide_cdn_rewrite ) {
foreach ( (array) $sources as $width => $source ) {
$sources[ $width ]['url'] = $wpide_cdn_rewrite( $source['url'] );
}
return $sources;
}, 99 );
add_filter( 'the_content', function ( $content ) use ( $wpide_cdn_url ) {
$uploads = wp_get_upload_dir();
$from = set_url_scheme( $uploads['baseurl'], 'https' );
$to = untrailingslashit( $wpide_cdn_url ) . wp_make_link_relative( $from );
return str_replace( array( $from, set_url_scheme( $from, 'http' ) ), $to, $content );
}, 99 );
}
Notes
Create a pull zone that points to your site first and set $wpide_cdn_url to its address; admin pages and the block editor keep using your own domain.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.