Skip to content

Instantly share code, notes, and snippets.

@patrickfreitasdev
Last active April 13, 2024 08:35
Show Gist options
  • Save patrickfreitasdev/0a53cbde3840332115bf0535e44b7f17 to your computer and use it in GitHub Desktop.
Save patrickfreitasdev/0a53cbde3840332115bf0535e44b7f17 to your computer and use it in GitHub Desktop.
<?php
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_preload_featured_image_with_cdn')) {
function wp_smush_preload_featured_image_with_cdn($image_id)
{
$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);
}
// 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);
echo '
<link rel="preload" as="image" href="' . $srcst[0] . '"
imagesrcset="' . implode(', ', $srcst) . '" imagesizes="' . $sizes . '" >';
}
}
add_action('wp_head', function () {
// page_id => image_id
$image_mapping = array(
2720 => 53915,
);
//get current page id
$page_id = get_the_ID();
if (isset($image_mapping[$page_id])) {
$image_id = $image_mapping[$page_id];
} else {
// get featured image id
$image_id = get_post_thumbnail_id();
}
if (!$image_id) {
return;
}
// if everything is fine then preload the image
wp_smush_preload_featured_image_with_cdn($image_id);
}, 0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment