Skip to content

Instantly share code, notes, and snippets.

@tboulogne
Forked from frankiejarrett/cdn-baseurl.php
Created December 31, 2018 10:59
Show Gist options
  • Select an option

  • Save tboulogne/72396b0f0bbf5c39cc4c2ec17512d415 to your computer and use it in GitHub Desktop.

Select an option

Save tboulogne/72396b0f0bbf5c39cc4c2ec17512d415 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