-
-
Save tboulogne/72396b0f0bbf5c39cc4c2ec17512d415 to your computer and use it in GitHub Desktop.
Filter the media uploads baseurl to point to a CDN
This file contains hidden or 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