Archived topic
Preload Blog Post Attachment Image on Every Post/Page
3 replies · Started by David on August 20, 2020
This works, apart from minor console error.
<?php
$attachment_image = wp_get_attachment_url( get_post_thumbnail_id() );
?>
<link rel=”preload” as=”image” href=”<?php echo esc_url( $attachment_image ); ?>”>
Place the code in header.php in the head section.
** If the attachment image is empty, it will show a warning in the console for incorrect preload value.
Answer: this now only runs if there is an active thumbnail. No more errors!
<?php if (has_post_thumbnail()) {
$attachment_image = wp_get_attachment_url( get_post_thumbnail_id() );
echo '<link rel="preload" as="image" href="'.$attachment_image.'">';
} ?>
Looks good :)
Glad to hear you found a solution.
Hi David,
Yes, I'm over the moon with my first ever snippet. All 3 x lines of it. :)
Should be useful to anyone wishing to improve upon their LCP times in PageSpeed Insights.
Thanks, D