How to use SRCSET with get_the_post_thumbnail()?

My wordpress theme uses get_the_post_thumbnail() to display Thumbnails on Posts.

I have set custom image sizes but running it through Lighthouse gives following error.

Serves images with low resolution Image natural dimensions should be proportional to the display size and the pixel ratio to maximize image clarity.

My innitial approach was to set Serves images with

get_the_post_thumbnail($ID, 'large');

This effects my largest contentful paint and increases page size, thus impacting my performance.

I need to strike a balance.

So is their a way to include multiple thumbnail sizes, and let wordpress choose the one thats best for user display and show the perfect size to user?

Topic thumbnails post-thumbnails php html theme-development Wordpress

Category Web


Found the solution myself.

Wordpress by defauly has multiple sizes. All we need to is add src.

The 3rd parameter of get_the_post_thumbnail has a array in which we can set attributed, including src set.

There's no direct way to add code for image urls in SRC SET. So we need to use wp_get_attachment_image_url inside the the get_the_post_thumbnail to get different image sizes for SRCSET.

After indvidually finding suitable sizes we add them according to their width as shown below..

Here we do not use px, as devices use different scalings and different pixel densities and complicate things. Instead w is used which allows the user's browser to automatically choose the suitable one among followings.

get_the_post_thumbnail(
                        null,
                        'large',
                        array( 
                            'srcset' => wp_get_attachment_image_url( get_post_thumbnail_id(), 'neve-blog' ) . ' 480w, ' .
                                wp_get_attachment_image_url( get_post_thumbnail_id(), 'thumbnail' ) . ' 640w, ' .
                                wp_get_attachment_image_url( get_post_thumbnail_id(), 'MedLarge') . ' 960w'
                        )
                    );

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.