# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Performance](https://wpide.com/library/category/performance/)
- Tags: preload, lcp, core-web-vitals
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/perf-preload-lcp-image-per-page/

## Code

```php
// 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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Preload a Chosen Hero Image per Page" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
