Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.