performance – How to preload images through Code Snippets wp_head for specific pages?


Website Structure

My WordPress website is used as presentation and portfolio for my graphic design services. Visual impact is important for me, so most of my pages contain big background hero image as first impresions and/or entrance animations.


Is relevant to share that all of the pages have two versions: one for english and one for spanish. It matters because I’m trying to preload specific images for both versions of a page (example: Contact page in english and Contact page in spanish both contain the same images)

Relevant Plugin for the topic

Code Snippets is the plugin I’ll be using to add the preload tag to the headers.

WebP Converter for Media is the plugin I use for compression, replacing files in standard JPEG, and PNG formats with WebP format.

Even though I serve static Cached versions of the website and use a compression plugin to minify the images weight, the very first images of each page load on the go (for example: in the middle of the entrance animation) and ruins a big part of the experience.

Here you can see one of my website’s pages to understand what I mean.

I need to preload those “first impression” images by adding a <link> tag using rel="preload", specifying the URLs for each of those images. The tag should only be added to the page that uses those images.

I know nothing of PHP, so the following code might have several rookie mistakes because it’s a copy-paste of different articles I’ve found.

(the code is meant to be inside a CodeSnippets snippet, aiming for the Contact page in spanish and english, with IDs equal to 5135 and 2061 respectivly)

add_action( 'wp_head', 'preload_page_contact' );
    function preload_page_contact(){
        if(is_single( array( 5135, 2061 )) {  ?>
            <link rel="preload" as="image" href="image1URLhere.webp" media="(min-width: 768px)"/>
            <link rel="preload" as="image" href="image2URLhere.webp" media="(min-width: 768px)"/>
            <link rel="preload" as="image" href="image3URLhere.webp" media="(min-width: 768px)"/>
        <?php  }
<?php } );

As far as I know the following code targets a specific page with ID=5135

if(is_single( '5135' )) {  ?>

But I need to target both english and spanish version. So I read that the following array returns true if it matches one or the other:

if(is_single( array( 5135, 2061 )) {  ?>

It doesn’t work. It states that “e” is undefined. So I’m probably missing something.

An extra question I’ve got concerning this very topic is the following:

Should I use the URL of the original image (PNG/JPG) or the URL of the compressed (WEBP)?

Ernest 1 month 2021-10-23T18:26:23-05:00 0 Answers 0 views 0

Leave an answer