Last active
June 20, 2024 03:24
-
-
Save zacscott/abb94e6289bcd129f4e7ba2680d65290 to your computer and use it in GitHub Desktop.
Use the WP.com Photon image CDN without installing JetPack
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 | |
/** | |
* Plugin Name: Photon CDN | |
* Version: 1.1 | |
* Description: Use the WP.com Photon image CDN without installing JetPack | |
* Author: Zachary Scott | |
*/ | |
namespace zacscott; | |
/** | |
* Driver class for the plugin. | |
* | |
* @author Zachary Scott <zac@zacscott.net> | |
*/ | |
class PhotonCDN { | |
/** | |
* The max number of image servers WP.com have (at time of writing it is 4) | |
* So the servers as i0.wp.com, i1.wp.com, i2.wp.com, i3.wp.com | |
*/ | |
const MAXSRV = 4; | |
function __construct() { | |
add_action( 'wp_head', array( $this, 'dns_prefetch' ) ); | |
add_action( 'template_redirect', array( $this, 'start_buffering' ) ); | |
} | |
// Adds the DNS prefetch meta fields for the WP.com servers | |
function dns_prefetch() { | |
for ( $srv = 0; $srv < self::MAXSRV; $srv++ ) : | |
$domain = "i{$srv}.wp.com"; | |
?> | |
<link rel='dns-prefetch' href='//<?php echo esc_attr( $domain ) ?>' /> | |
<?php | |
endfor; | |
} | |
// Start the output buffering | |
function start_buffering() { | |
ob_start( array( $this, 'process_output' ) ); | |
} | |
// Processes the output buffer, replacing all matching images with URLs | |
// Pointing to wp.com | |
function process_output( $buffer ) { | |
// Get the content directory URL minus the http:// | |
$content_url = content_url(); | |
$content_url = str_replace( 'http://', '', $content_url ); | |
$content_url = str_replace( 'https://', '', $content_url ); | |
// Replace references to images on our servers with the wp.com CDN | |
return preg_replace_callback( | |
'{'. $content_url .'/.+\.(jpg|jpeg|png|gif|ico|bmp)}i', | |
array( $this, 'replace' ), | |
$buffer | |
); | |
} | |
// Replaces a single image URL match | |
function replace( $matches ) { | |
// Grab the parsed image URL | |
$url = isset( $matches[0] ) ? $matches[0] : ''; | |
// Pick a random server | |
srand( crc32( $url ) ); // Best if we always use same server for this image | |
$server = rand( 0, self::MAXSRV-1 ); | |
// Build the wp.com URL, as return as the replacement | |
return "i{$server}.wp.com/{$url}"; | |
} | |
} | |
// Boot | |
new PhotonCDN(); |
This goes against their Terms of Use policy.
good idea thanks.
Works only on some image and don't work with woocommerce...any idea?
Update it
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This thing helped me a lot. Thanks to the author.