We extend the WP API with custom fields, some of these fields contain image URL’s of image HTML tags with srcsets. For now we wrote the following code to achieve that:
class Cdn {
public static function addHooks() {
add_filter( 'wp_get_attachment_image_src', [ Cdn::class, 'maybeRewriteUrl' ], 10, 1 );
add_filter( 'wp_calculate_image_srcset', [ Cdn::class, 'imageSrcSet' ], 10, 5 );
add_filter( 'acf/format_value', [ Cdn::class, 'formatAcfValue' ], 10, 3 );
}
public static function maybeRewriteUrl( $image ) {
if ( class_exists( 'CDN_Enabler' ) ) {
$rewrite = \CDN_Enabler::get_rewriter();
$image[0] = $rewrite->rewrite_url( $image );
}
return $image;
}
public static function imageSrcSet( $sources, $size_array, $image_src, $image_meta, $attachment_id ) {
if ( class_exists( 'CDN_Enabler' ) ) {
$rewrite = \CDN_Enabler::get_rewriter();
$sources = array_map( function ( $src ) use ( $rewrite ) {
$image = [
0 => $src['url'],
];
$src['url'] = $rewrite->rewrite_url( $image );
return $src;
}, $sources );
}
return $sources;
}
public static function formatAcfValue( $value, $post_id, $field ) {
if ( $field['type'] === 'wysiwyg' && class_exists( 'CDN_Enabler' ) ) {
$rewrite = \CDN_Enabler::get_rewriter();
$value = $rewrite->rewrite( $value );
}
return $value;
}
}