• Hi there! I’m trying to optimize our website by preloading the featured image but it appears to be returning the JPG URL when it’s the WEBP that is displayed. When the page is loaded, I see this warning in the browser’s console log:

    The resource {CDN URL REDACTED}/GettyImages-1061745418-1142x493.jpg was preloaded using link preload but not used within a few seconds from the window’s load event. Please make sure it has an appropriate as value and it is preloaded intentionally.

    When I go to inspect the file that is visible on the page, I see the extension as GettyImages-1061745418-1142x493.jpg.webp in the HTML for the image element.

    I’m using WordPress’s native functions for retrieving the URL, specifically:

    global $post;
    if(has_post_thumbnail($post->ID)) {
        $image_size = 'hero';
        $featured_image_id = get_post_thumbnail_id($post->ID);
        $featured_image_url = wp_get_attachment_image_src($featured_image_id, $image_size);
        echo sprintf(
            '<link id="preload-featured-image" rel="preload" as="image" href="%s" data-size="%s" data-id="%s" />',
            $featured_image_url,
            $image_size,
            $featured_image_id
        );
    }

    And then when it’s displayed on the frontend, it also uses WordPress functions:

    global $post;
    if(has_post_thumbnail($post->ID)) {
        $featured_image_id = get_post_thumbnail_id($post->ID);
        echo wp_get_attachment_image($featured_image_id, 'hero', false, array(
            'loading' =>  false,
            'alt' => get_post_meta($featured_image_id, '_wp_attachment_image_alt', true)
        ));
    }

    I guess what I’m saying is that I’m experiencing inconsistencies with wp_get_attachment_image_src() and wp_get_attachment_image(). When I get the HTML for the whole image tag in the latter, it correctly loads the WEBP format, but when I use the former to get just the URL, it only gives me the original JPG format.

    In my settings, I’ve got the box checked for WebP Conversion.

    Under WebP Delivery Method, I’ve got the box checked for JS WebP Rewriting since we’re using a CDN (seemed like the right choice, maybe this is the issue?)

    And then I’ve got my uploads and active theme directory with the CDN hostname set in WebP URLs.

    Any help is appreciated. Thanks!

Viewing 4 replies - 1 through 4 (of 4 total)
  • Plugin Support adamewww

    (@adamewww)

    Hi Tessa,

    Unfortunately, you can’t use Preload and JS WebP together since it’s effectively changing the URL (from .jpg, to .jpg.webp).

    Thread Starter Tessa (they/them), AuRise Creative

    (@tessawatkinsllc)

    Ah, yeah. I meant to reply. I unchecked that box and they did return the same URLs, but now I’m trying to figure out how I can modify the delivery and which would make the most sense for my client’s site.

    I’m curious about using HTML-based delivery but I don’t know how to enable that from the settings. I’d also rather not enable the Force WebP option because it says WebP images aren’t always created, especially in situations when the original image is already smaller than the generated WebP. For the same reason, I also don’t want to hardcode the .webp extension in my source code.

    I’m imagining that I’d check a box somewhere in your plugin’s settings and then the appropriate URL, if the WebP version exists, would be returned.

    Is that possible or should I do that in my source code using file_exists()?

    Thanks for your quick feedback!

    Plugin Support adamewww

    (@adamewww)

    I apologize for the delay in responding, the week has already gotten away from me.

    I’m not certain given the preload request that there is an option. JS WebP is the best option for that, however, you can try the picture webp option. Instead of using JS it puts your images in an HTML <picture> element. For all of the WebP options, it works as you desire.. the only issue being with preloading since it has to have a consistent URL.

    Thread Starter Tessa (they/them), AuRise Creative

    (@tessawatkinsllc)

    No worries, I think I’ve sorted it out for my use case. I wrote this function to check if a file with the .webp extension exists by hooking into the wp_get_attachment_image_src filter with a later priority. This filter is used in both wp_get_attachment_image_src() and wp_get_attachment_image() when getting the URL of the image so it returns a consistent JPG or WebP URL.

    Since I’m using a CDN, I’m just checking the file’s response headers and considering success as anything below 400: so informational, successful, and redirections are fine, but client or server errors are not.

    That way, whether I use WordPress’s native functions for getting the URL or the img element, it pulls the generated WebP file, or the original if it doesn’t exist.

    /**
     * Filters the attachment image source result.
     *
     * @see https://developer.ww.wp.xz.cn/reference/functions/wp_get_attachment_image/
     *
     * @param array|false  $image Array of image data, or boolean false if no image is available. $image = {
     *     @type string $0 Image source URL.
     *     @type int $1 Image width in pixels.
     *     @type int $2 Image height in pixels.
     *     @type bool $3 Whether the image is a resized image.
     * }
     *
     * @return array|false A possibly modified array of image data, or boolean false if no image is available.
     */
    function au_get_maybe_webp_url($image)
    {
        if (
            is_array($image) && count($image) && // Ensure image data was found
            in_array(pathinfo($image[0], PATHINFO_EXTENSION), array('jpg', 'jpeg', 'png')) // Only check for these image extensions
        ) {
            $maybe_webp = $image[0] . '.webp';
            $file_headers = @get_headers($maybe_webp);
            if (
                $file_headers !== false // Ensure get_headers() didn't fail
                && count($response = explode(' ', $file_headers[0])) === 3 // Define status and that we got all 3 parts, e.g. "HTTPS/1.1 200 OK" => ['HTTPS/1.1','200','OK']
                && is_numeric($response[1]) // Check that the response header is numeric
                && round(intval($response[1]), -2, PHP_ROUND_HALF_DOWN) < 400 // Check that it's in the 100 (informational), 200 (successful), or 300 (redirects) categories
            ) {
                $image[0] = $maybe_webp; // Use the WebP extension
            }
        }
        return $image;
    }
    add_filter('wp_get_attachment_image_src', 'au_get_maybe_webp_url', 20, 1);

    Thanks!

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

The topic ‘Wrong URL is returned when preloading featured image’ is closed to new replies.