How to Make Featured Image Responsive in WordPress

Featured images are not responsive out of the box in WordPress. There is a function add_image_size() to make copies of the featured image with different dimensions, but when it comes to viewing the posts in various devices the end results are often poor.

There are solutions involving plugins but i am one for simpler solutions!

Here is a quick way to make any featured image responsive in WordPress. It involves 2 parts. One – get the post thumbnail id, Two – get the post attachment url for that id.

Inside the default WordPress loop

$thumbId = get_post_thumbnail_id();
$thumbUrl= wp_get_attachment_url( $thumbId );

Outside the WordPress loop

global $post;
$thumbId = get_post_thumbnail_id( $post->ID );
$thumbUrl = wp_get_attachment_url( $thumbId );

Then use the url as image source for your featured image and set the image width at 100% .

<img style="width: 100%" src="<?php echo $thumbUrl?>" />

You can of course remove the inline styling and use the width in a CSS class.

Leave a Reply

Your email address will not be published. Required fields are marked *