Skip to content

Instantly share code, notes, and snippets.

@fjarrett
Created July 20, 2017 16:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fjarrett/b58b55fc70da46eaa0e8a3ae1422d921 to your computer and use it in GitHub Desktop.
Save fjarrett/b58b55fc70da46eaa0e8a3ae1422d921 to your computer and use it in GitHub Desktop.
Filter the media uploads baseurl to point to a CDN
<?php
// Turn ON: $ wp option update cdn_baseurl https://abc123.cloudfront.net/wp-content/uploads
// Turn OFF: $ wp option delete cdn_baseurl
$cdn_baseurl = get_option( 'cdn_baseurl' );
if ( ! $cdn_baseurl ) {
return;
}
add_action( 'template_redirect', function () use ( $cdn_baseurl ) {
$pattern = sprintf(
'#https?://%s/(.+\.(?:gif|ico|jpg|jpeg|png))#',
preg_replace( '#^https?://#', '', str_replace( '.', '\.', WP_CONTENT_URL . '/uploads' ) )
);
ob_start( function ( $content ) use ( $pattern, $cdn_baseurl ) {
return preg_replace( $pattern, "{$cdn_baseurl}/$1", $content );
} );
}, -PHP_INT_MAX );
add_filter( 'upload_dir', function ( $uploads ) use ( $cdn_baseurl ) {
$uploads['baseurl'] = $cdn_baseurl;
return $uploads;
}, -PHP_INT_MAX );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment