Home / Admin / Preload First Post Image
Duplicate Snippet

Embed Snippet on Your Site

Preload First Post Image

Preload First Post Image

Code Preview
php
<?php
function preload_first_content_image() {
    if (is_single()) {
        $post = get_post();
        if ($post) {
            // Get post content
            $content = $post->post_content;
            
            // Find first image in the content
            preg_match_all('/<img.+?src=[\'"]([^\'"]+)[\'"].*?>/i', $content, $matches);
            
            if (!empty($matches[1])) {
                $first_image = $matches[1][0];
                echo '<link rel="preload" as="image" fetchpriority="high" href="' . esc_url($first_image) . '">';
            }
        }
    }
}
add_action('wp_head', 'preload_first_content_image', 1);

Comments

Add a Comment