Last active
July 10, 2024 10:24
-
-
Save erikyo/31bc708ced5b277526ad297a4a83705b to your computer and use it in GitHub Desktop.
Wordpress preload featured image (src and srcset)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // Preload the Wordpress post featured image (works both with src and srcset) | |
| // ref. https://web.dev/preload-responsive-images/ | |
| add_action('wp_head', function () { | |
| if (has_post_thumbnail()) { | |
| $thumb_id = get_post_thumbnail_id( get_the_ID() ); | |
| $featured_img_src = wp_get_attachment_image_src( $thumb_id, 'large' )[0]; | |
| $featured_img_srcset = wp_get_attachment_image_srcset( $thumb_id ); | |
| printf('<link rel="preload" as="image" importance="high" href="%s" srcset="%s" />', $featured_img_src, $featured_img_srcset ); | |
| } | |
| }, 1); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment