Created
July 20, 2017 16:53
-
-
Save fjarrett/b58b55fc70da46eaa0e8a3ae1422d921 to your computer and use it in GitHub Desktop.
Filter the media uploads baseurl to point to a CDN
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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