Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@halimjr halimjr commented Mar 16, 2018

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

@pau1phi11ips

This comment has been minimized.

Copy link

@pau1phi11ips pau1phi11ips commented Dec 4, 2018

This goes against their Terms of Use policy.

@fatihtoprak

This comment has been minimized.

Copy link

@fatihtoprak fatihtoprak commented Feb 6, 2019

good idea thanks.

@santimonevito

This comment has been minimized.

Copy link

@santimonevito santimonevito commented Feb 14, 2019

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

@adityayt

This comment has been minimized.

Copy link

@adityayt adityayt commented Jul 11, 2021

Update it

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