Preload each post's featured image so it appears sooner, and open early connections to the outside origins your pages really use.
// Open early connections to outside origins your pages always use. Edit this list.
add_filter( 'wp_resource_hints', function ( array $urls, string $relation_type ): array {
$origins = [
'preconnect' => [
// [ 'href' => 'https://fonts.gstatic.com', 'crossorigin' => 'anonymous' ],
],
'dns-prefetch' => [
// 'https://cdn.example.com',
],
];
return array_merge( $urls, $origins[ $relation_type ] ?? [] );
}, 10, 2 );
// Preload the featured image on single posts and pages, where it is usually the largest image.
add_action( 'wp_head', function (): void {
if ( ! is_singular() || ! has_post_thumbnail() ) {
return;
}
$id = get_post_thumbnail_id();
$image = wp_get_attachment_image_src( $id, 'large' );
$srcset = wp_get_attachment_image_srcset( $id, 'large' );
if ( ! $image ) {
return;
}
printf(
'<link rel="preload" as="image" href="%s"%s fetchpriority="high">' . "\n",
esc_url( $image[0] ),
$srcset ? ' imagesrcset="' . esc_attr( $srcset ) . '" imagesizes="(max-width: 1024px) 100vw, 1024px"' : ''
);
}, 1 );
Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.
Two small hints can make pages feel faster. Preloading the main image tells the browser to start downloading it straight away instead of waiting to discover it in the HTML, which helps Largest Contentful Paint. Preconnecting to an outside origin you always use, such as a CDN, sets up that connection while the page is still loading.
The wp_resource_hints filter adds origins to the hints WordPress already prints. The list starts empty: only add origins every page actually loads from. Preconnecting to something a page never uses wastes a connection.
On single posts and pages, the second part prints a preload tag for the featured image, including its srcset so phones download a smaller version. fetchpriority="high" moves it to the front of the queue.
The previous version preconnected to Google Fonts and Google Analytics on every site, whether or not they were used, and preloaded theme files that often didn’t exist, which shows warnings in the browser console.
imagesizes to match how wide the image displays in your theme.Open a post with a featured image, view the source and look for rel="preload" near the top of the head. In Chrome DevTools, the image should appear early in the Network panel with “High” priority.