Skip to content

Instantly share code, notes, and snippets.

@zacscott
Last active January 30, 2024 10:12
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save zacscott/abb94e6289bcd129f4e7ba2680d65290 to your computer and use it in GitHub Desktop.
Save zacscott/abb94e6289bcd129f4e7ba2680d65290 to your computer and use it in GitHub Desktop.
Use the WP.com Photon image CDN without installing JetPack
<?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();
@halimjr
Copy link

halimjr commented Mar 16, 2018

This thing helped me a lot. Thanks to the author.

@pau1phi11ips
Copy link

This goes against their Terms of Use policy.

@santimonevito
Copy link

Works only on some image and don't work with woocommerce...any idea?

@adityayt
Copy link

Update it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment