Skip to content

Instantly share code, notes, and snippets.

@wichaksono
Last active September 17, 2022 09:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wichaksono/89b2475efd97db62e2ef81af1945b8fb to your computer and use it in GitHub Desktop.
Save wichaksono/89b2475efd97db62e2ef81af1945b8fb to your computer and use it in GitHub Desktop.
CDN statically
<?php
/**
* Taruh di functions.php paling bawah
*/
/**
* Mengubah Semua URL image di konten menjadi berCDN
*/
function cdn_on_the_fly($content) {
$pattern = '#(\-(\d+)x(\d+))?\.((?:jpg|gif|png|webp|jpeg))#';
return preg_replace($pattern, '.$4?format=webp&quality=80&w=$2&h=$3', $content);
}
function replace_all_image_in_content($content) {
$pattern = "#https:\/\/((.*)\.(?:jpg|gif|png|webp|jpeg))#";
$content = preg_replace($pattern, '//cdn.statically.io/img/${1}', $content);
return $content;
}
add_filter('the_content', 'replace_all_image_in_content' );
/**
* Mengubah URL image di thumbnail menjadi berCDN
*/
function replace_image_in_thumbnail($image) {
$cdn_image = '//cdn.statically.io/img/';
if ( $image[3] ) {
$image_size = sprintf('-%dx%d', $image[1], $image[2]);
$trim_url = str_replace( $image_size, '', $image[0] );
} else {
$trim_url = $image[0];
}
$image[0] = str_replace(['http://', 'https://'], $cdn_image, $trim_url . '?format=webp&w='. $image[1] .'&h='. $image[2] .'&quality=80' );
return $image;
}
add_filter('wp_get_attachment_image_src', 'replace_image_in_thumbnail');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment