How To Get The Post Thumbnail URL in WordPress

I was working on a project that I wanted to enable lazy loading using a specific jQuery plugin, so I needed to get the thumbnail URL for all of my posts.

The feature was loading around 300 articles from a custom post type using a shortcode. Every article had a featured image. Which meant that the page was loading around 300 extra images that would not always be used.

A little intro to lazy loading

Lazy loading is a way of using JavaScript to load images only after they enter the viewport. The viewport is what the user can actually see on their screen.

If you have a gallery and on the screen you have 25 rows of 4 images, each row being 250px tall, you can start the page by just loading what can actually be seen on screen (probably 3-4 rows) and only load the remainder as people scroll down. It saves a lot on what your users need to download, so you’re saving bandwidth and browser rendering time. Always a good thing.

Why not use a WordPress plugin?

If you look at the plugin repository there are a few plugins that handle lazy loading for you. To be honest I didn’t check any of them out. I wanted to be able to have absolute control over which images get lazy loaded, because it’s just the thumbnail URL loaded in 2 modal windows.

On to my solution

The way I handle it is to load the Lazy Load jQuery plugin and just apply the special code to that.

In my functions.php I added the following code to get the new javascript loading. It has a dependency on jQuery, so that’s important to add.

The next step is the JavaScript that makes it work.

It just looks for any img tag with the lazy class and applies the lazy load rules. There are a lot of arguments you can pass to the plugin that are all explained on their site.

Now comes the magic in WordPress. Normally to get the thumbnail to show you would just use

Getting the thumbnail URL

That won’t work for this because we need to get the thumbnail URL and switch everything up. Fortunately WordPress makes it easy. The new code is

We use wp_get_attachment_image_src() to get the url based on get_post_thumbnail_id(). In our class attribute we need to assign the lazy class so the JavaScript knows to process it.

Now the page is downloading several hundred fewer images and rendering a lot faster. All with just a couple little changes.

There are a lot more things you can do by getting the thumbnail URL. You can customize things far beyond what adding a class would allow you to do.

Leave a Reply