How to use SRCSET with get_the_post_thumbnail()?

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'
                        )
                    );

Leave a Comment