• Resolved pukos

    (@pukos)


    As is the title is it possible to preload the featured image? How?
    I use the JS WebP Rewriting and Picture WebP Rewriting to show WebP.

    In the past I used this script but now is not suitable because it preload the JPG version:

    add_action( 'wp_head', function(){
    $featured_img_url = get_the_post_thumbnail_url(get_the_ID(),'full');
    echo '<link rel="preload" as="image" href="'.$featured_img_url.'"/>';
    })
Viewing 3 replies - 1 through 3 (of 3 total)
  • Plugin Support adamewww

    (@adamewww)

    I’m fairly certain there isn’t a way unless you hardcode the actual WebP version in your site and then preload that. The JS WebP doesn’t happen until the JS actually runs (which defeats the purpose of preloading).

    Thread Starter pukos

    (@pukos)

    Thanks to chatgpt I’m testing this function that should cover 99% of cases. What do you think?

    function preload_featured_image() {
        global $post;
        $featured_image_url = get_the_post_thumbnail_url($post->ID, 'full');
    
        if ($featured_image_url) {
            $path = parse_url($featured_image_url, PHP_URL_PATH);
            $file_path = $_SERVER['DOCUMENT_ROOT'] . $path;
            $webp_file_path = str_replace('.jpg', '.jpg.webp', $file_path);
    
            if (file_exists($webp_file_path)) {
                $webp_image_url = str_replace('.jpg', '.jpg.webp', $featured_image_url);
                echo '<link rel="preload" href="' . esc_url($webp_image_url) . '" as="image" type="image/webp" />';
            } else {
                echo '<link rel="preload" href="' . esc_url($featured_image_url) . '" as="image" type="image/jpeg" />';
            }
        }
    }
    
    add_action('wp_head', 'preload_featured_image');
    Plugin Support adamewww

    (@adamewww)

    It looks like it’s just doing that “hardcoding” part for you but if it works for what you want, great!

Viewing 3 replies - 1 through 3 (of 3 total)

The topic ‘Preload featured image WebP’ is closed to new replies.