Hi @jek-fdrv,
We have an update from our developers, on Smush you can auto-generate image sizes with CDN.
Please add the following snippet code inside your theme’s functions.php file.
if ( ! function_exists( 'wp_smush_cdn' ) ) {
function wp_smush_cdn() {
static $smush_cdn;
if ( is_null( $smush_cdn ) && class_exists( '\WP_Smush' ) ) {
$smush_cdn = \WP_Smush::get_instance()->core()->mod->cdn;
}
return $smush_cdn;
}
}
if ( ! function_exists( 'wp_smush_generate_cdn_image_size' ) ) {
function wp_smush_generate_cdn_image_size( $image_id, $image_size ) {
$smush_cdn = wp_smush_cdn();
static $image;
if ( isset( $image[ $image_id ] ) ) {
$image_url = $image[ $image_id ];
} else {
$image = array();
$image_url = wp_get_attachment_url( $image_id );
$image[ $image_id ] = $image_url;
}
if ( ! $smush_cdn ) {
return $image_url;
}
$image_size = (array) $image_size;
$image_size[] = 0;
list( $width, $height ) = $image_size;
$args = array();
// $args['webp'] = 1; // Already set it via Smush CDN admin.
if ( ! empty( $width ) ) {
$args['size'] = "{$width}x{$height}";
}
$cdn_resized_url = $smush_cdn->generate_cdn_url( $image_url, $args );
return $cdn_resized_url;
}
}
if ( ! function_exists( 'wp_smush_get_right_image' ) ) {
function wp_smush_get_right_image( $image_id ) {
static $enable_lazyload;
// $enable_lazyload = true;
if ( is_null( $enable_lazyload ) && class_exists( '\Smush\Core\Settings' ) ) {
$enable_lazyload = Smush\Core\Settings::get_instance()->get( 'lazy_load' );
} else {
$enable_lazyload = false;
}
$popular_device_sizes = array( 0, 1440, 921, 769, 390 );// Add 0 to generate full size.
foreach ( $popular_device_sizes as $img_size ) {
$srcst[] = wp_smush_generate_cdn_image_size( $image_id, $img_size );
}
$class_name = '';
if ( $enable_lazyload ) {
$class_name .= ' lazyload';
}
// Enter content width.
$content_width = ! empty( $GLOBALS['content_width'] ) ? (int) $GLOBALS['content_width'] : 1920;
// Avoid situations, when themes misuse the global.
if ( 0 === $content_width ) {
$content_width = 1920;
}
$sizes = sprintf( '(max-width: %1$dpx) 100vw, %1$dpx', $content_width );
return '
<img class="' . trim( $class_name ) . '" src="' . $srcst[0] . '"
srcset="' . implode( ', ', $srcst ) . '" sizes="' . $sizes . '" >';
}
}
And then the following code can help create the src set list of images.
wp_smush_generate_cdn_image_size( 174, 600 );// Generate image size 600x0 (width = 600, height = auto)
wp_smush_generate_cdn_image_size( 174, array(600, 400 ) );// generate image size 600x400
wp_smush_get_right_image( 174 );
I hope that helps. Please feel free to let us know if you need any clarification.
Kind Regards,
Nebu John