0

I wrote the script below to replace the URL of the images in the post content with the WordPress CDN link. (Yes, I know the Jetpack, but in my case I can not use it)

<?php
add_filter('the_content','cdn_imageurl',9999);
function cdn_imageurl($content) {
    // Prepare url for regex
    $url = str_replace("/", "\/", get_site_url());
    $url = str_replace(".", "\.", $url);

    // Find the images that matches the boundaries of the CDN
    $content = preg_replace_callback("@(?i)<img.+?(src=[\"'](".$url."((?![\"']).)*\/wp-content\/uploads\/((?![\"']).)*\.(gif|jpe?g|png))[\"']).+?>@",'cdn_imageurl_replace',$content);
    return $content;
}

function cdn_imageurl_replace($matches) {
    // Do not proceed if src is empty
    if(!$matches[2]) { return $matches[0]; }

    // Prepare url for regex
    $url = str_replace("/", "\/", get_site_url());
    $url = str_replace(".", "\.", $url);

    // Find the images that matches the boundaries of the CDN (child)
    $matches = preg_replace_callback("@(?i)((src|data-orig-file|data-medium-file|data-large-file|srcset)=[\"'](".$url."((?![\"']).)*\/wp-content\/uploads\/((?![\"']).)*)[\"'])@",'cdn_imageurl_replace_child',$matches);
    return $matches[0];
}

function cdn_imageurl_replace_child($matches) {
    // Do not proceed if src is empty
    if(!$matches[3]) { return $matches[0]; }

    // Generates cdn subdomain number
    $url = parse_url(get_site_url());
    $url = str_replace("www.", "", $url['host']);
    srand(crc32(basename($url)));
    $static_rand = rand(0,2);
    srand(); // this resets everything that relies on this, like array_rand() and shuffle()

    // Replaces the protocol with cdn url
    $wp = '//i'.$static_rand.'.wp.com/';
    $url_replace = preg_replace("/(http:\/\/|https:\/\/)/i", $wp, $matches[3]);
    $replace = str_replace($matches[3],$url_replace,$matches[0]);
    return $replace;
}

It works great for the_widget filter. However, how can I adapt my code to also replace the images urls in the widgets and post_thumbnail?

I've tried to do this in countless ways. I tried to use the the_widget and the_post_thumbnail filters, but without success.

  • I was able to do this using the pre_option_upload_url_path filter. However, with this filter I can not identify the type of image. And I need to check this out because the WordPress CDN only accepts some types of images. – Rodrigo Gomes Jul 26 '18 at 22:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.