Preload a Chosen Hero Image per Page
Adds a "Preload hero image" field to the post and page editor; when filled in with an image URL, that image is preloaded with high priority on that page, improving Largest Contentful Paint for pages whose main image is not the featured image.
Opens WPIDE on
Code
// Post types that get the field.
$wpide_lcp_types = array( 'post', 'page' );
add_action( 'add_meta_boxes', function () use ( $wpide_lcp_types ) {
add_meta_box( 'wpide-lcp-preload', 'Preload hero image', function ( $post ) {
wp_nonce_field( 'wpide_lcp_preload', 'wpide_lcp_nonce' );
printf(
'<label for="wpide-lcp-url" class="screen-reader-text">Hero image URL</label><input type="url" id="wpide-lcp-url" name="wpide_lcp_url" class="widefat" value="%s" placeholder="https://..."><p class="description">URL of the large image at the top of this page.</p>',
esc_attr( get_post_meta( $post->ID, '_wpide_lcp_url', true ) )
);
}, $wpide_lcp_types, 'side', 'low' );
} );
add_action( 'save_post', function ( $post_id ) {
if ( ! isset( $_POST['wpide_lcp_nonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['wpide_lcp_nonce'] ), 'wpide_lcp_preload' ) || ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
$url = isset( $_POST['wpide_lcp_url'] ) ? esc_url_raw( wp_unslash( $_POST['wpide_lcp_url'] ) ) : '';
if ( $url ) {
update_post_meta( $post_id, '_wpide_lcp_url', $url );
} else {
delete_post_meta( $post_id, '_wpide_lcp_url' );
}
} );
add_filter( 'wp_preload_resources', function ( $resources ) {
if ( ! is_singular() ) {
return $resources;
}
$url = get_post_meta( get_queried_object_id(), '_wpide_lcp_url', true );
if ( $url ) {
$resources[] = array( 'href' => $url, 'as' => 'image', 'fetchpriority' => 'high' );
}
return $resources;
} );
Notes
Use it for hero images set in page builders or cover blocks; preloading the wrong image wastes bandwidth, so pick the one visible at the top.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.