Preload First Image on Front Page

This snippet preloads the first image on your WordPress homepage content to improve Largest Contentful Paint. It scans for the first <img>, retrieves its URL (and srcset/sizes if available), and injects a <link rel="preload" as="image"> tag into the page head. This ensures the hero image loads earlier, boosting Core Web Vitals performance.

				
					/**
 * Preload the first image in homepage content (for LCP optimization).
 */
add_action( 'wp_head', function() {
	if ( ! is_front_page() ) {
		return;
	}

	global $post;

	if ( empty( $post->post_content ) ) {
		return;
	}

	// Extract the first <img fetchpriority="high"> tag from content
	if ( preg_match( '/<img[^>]+src="([^"]+)"[^>]*>/i', $post->post_content, $matches ) ) {
		$img_url = esc_url( $matches[1] );

		// Try to get attachment ID from URL
		$attachment_id = attachment_url_to_postid( $img_url );

		if ( $attachment_id ) {
			// Use WordPress helpers to get srcset + sizes
			$srcset = wp_get_attachment_image_srcset( $attachment_id, 'full' );
			$sizes  = wp_get_attachment_image_sizes( $attachment_id, 'full' );

			printf(
				'<link rel="preload" as="image" href="%s"%s%s />' . "\n",
				$img_url,
				$srcset ? ' imagesrcset="' . esc_attr( $srcset ) . '"' : '',
				$sizes  ? ' imagesizes="' . esc_attr( $sizes ) . '"' : ''
			);
		} else {
			// Fallback: preload the raw image URL without srcset/sizes
			printf(
				'<link rel="preload" as="image" href="%s" />' . "\n",
				$img_url
			);
		}
	}
});
				
			

If this code helped you, or you have any questions on implementation, don’t hesitate to reach out.