Search code examples
wordpress

'src' is not available in $attr for wp_get_loading_optimization_attributes


I have tried to use code mentioned in dev note but it is not working, this is the snippet I have tried:

function set_fetchpriority_high_on_specific_image( $loading_attrs, $tag_name, $attr, $context ) {
    if ( 'img' === $tag_name ) {
        if (
            'the_content' === $context &&
            isset( $attr['src'] ) &&
            $attr['src'] === 'https://example.org/a-specific-image.jpg'
        ) {
            $loading_attrs['fetchpriority'] = 'high';
        } else {
            unset( $loading_attrs['fetchpriority'] );
        }
    }
    return $loading_attrs;
}
add_filter(
    'wp_get_loading_optimization_attributes',
    'set_fetchpriority_high_on_specific_image',
    10,
    4
);

I am not to add fetchpriority high by comparing the url of the image in WordPress using the hook.


Solution

  • Currently wp_img_tag_add_loading_optimization_attrs does not has src due to which the hook is not working, this is already reported to WordPress core.

    You can still achieve this by doing the following changes.

    1. Go to wp-includes/media.php file and here we need to add 'src' attribute by going to wp_img_tag_add_loading_optimization_attrs function and then add
    $src               = preg_match( '/ src=["\']?([^"\']*)/i', $image, $matche_src ) ? $matche_src[1] : null;
    

    just before the

    $width             = preg_match( '/ width=["\']([0-9]+)["\']/', $image, $match_width ) ? (int) $match_width[1] : null;
    
    1. then we need to replace
        $optimization_attrs = wp_get_loading_optimization_attributes(
            'img',
            array(
                'width'         => $width,
                'height'        => $height,
                'loading'       => $loading_val,
                'fetchpriority' => $fetchpriority_val,
                'decoding'      => $decoding_val,
            ),
            $context
        );
    

    with the given one.

        $optimization_attrs = wp_get_loading_optimization_attributes(
            'img',
            array(
                'src'           => $src,
                'width'         => $width,
                'height'        => $height,
                'loading'       => $loading_val,
                'fetchpriority' => $fetchpriority_val,
                'decoding'      => $decoding_val,
            ),
            $context
        );
    

    Please let me know if this works for you.