-
-
Save tboulogne/07383b796fee83689da9cc136f5474cc to your computer and use it in GitHub Desktop.
WordPress Must Use Plugin which rewrites asset URI's to CDN77.
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 | |
| /** | |
| * WordPress Must Use Plugin which rewrites asset URI's to CDN77. | |
| * | |
| * This is largely inspired my Mark Jaquith's WP_Stack CDN plugin | |
| * https://github.com/markjaquith/WP-Stack/blob/master/WordPress-Dropins/wp-stack-cdn.php | |
| * | |
| * Options that should be set in wp-config.php | |
| * CDN77_ENABLE - Set to TRUE if the CDN should be enabled | |
| * CDN77_DOMAIN - The domain name for the CDN77 subdomain in use | |
| * (can be | separated for rotating domains) | |
| */ | |
| // Hook on init to setup the output buffering for this plugin | |
| add_action( 'init', 'cdn77_rewrite_init', 5 ); | |
| if ( ! function_exists( 'cdn77_rewrite_init' ) ): | |
| function cdn77_rewrite_init() { | |
| // Only bother if the CDN is enabled | |
| if ( defined( 'CDN77_ENABLED' ) && CDN77_ENABLED ) { | |
| add_action( 'template_redirect', 'cdn77_rewrite_buffer_start' ); | |
| } | |
| } | |
| endif; | |
| // Define action for starting and flushing output buffers | |
| if ( ! function_exists( 'cdn77_rewrite_buffer_start' ) ): | |
| function cdn77_rewrite_buffer_flush( $content ) { | |
| // setup the domains that will be replaced | |
| $extensions = array( 'jpe?g', 'gif', 'png', 'css', 'bmp', 'js', 'ico' ); | |
| $domain = parse_url( get_bloginfo( 'url' ), PHP_URL_HOST ); | |
| $cdn = ( defined( 'CDN77_DOMAIN' ) ) ? explode( '|', CDN77_DOMAIN ) : NULL; // just in case | |
| if ( is_null( $cdn ) ) { | |
| return $content; | |
| } | |
| // how many replacement domains have been specfied | |
| $nDomains = count($cdn); $cdnIdx = 0; $rCount = 1; | |
| if ( 0 === $nDomains ) { | |
| return preg_replace( "#=([\"'])(https?://{$domain})?/([^/](?:(?!\\1).)+)\.(" . implode( '|', $extensions ) . ")(\?((?:(?!\\1).)+))?\\1#", | |
| '=$1//' . $cdn[$cdnIdx] . '/$3.$4$5$1', $content ); | |
| } else { | |
| // loop over the content until no more replacements are required | |
| while( $rCount > 0 ) { | |
| $content = preg_replace( "#=([\"'])(https?://{$domain})?/([^/](?:(?!\\1).)+)\.(" . implode( '|', $extensions ) . ")(\?((?:(?!\\1).)+))?\\1#", | |
| '=$1//' . $cdn[$cdnIdx] . '/$3.$4$5$1', $content, 1, $rCount ); | |
| $cdnIdx = ( $cdnIdx + 1) % $nDomains; | |
| } | |
| // and finally output the modified content | |
| return $content; | |
| } | |
| } | |
| function cdn77_rewrite_buffer_start() { | |
| ob_start( 'cdn77_rewrite_buffer_flush' ); | |
| } | |
| endif; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment