Remove automatic dimensions from WordPress Image attachments

a minute read

When you upload and add images in your WordPress posts, you might have noticed the dimensions that it adds to the image automatically. Same goes with the post thumbnails, they also carry some auto-generated thumbnail markup.

The dimension markup is nothing but the width and height attributes that resize images in the post. But these dimension attributes may create problems with a responsive layout. Take a look at the highlighted section in the below given code, that’s what I’m talking about:

<img width="300" height="200" src="http://localhost/wordpress/wp-content/uploads/2013/02/attachment-thumb.jpg" class="attachment-post-thumbnail wp-post-image" alt="Attachment Thumbnail" />

In such a situation, WordPress developers want those highlighted, hard-coded width & height attributes snipped from the image attachments. It can be achieved by adding a few lines of code to the functions.php of our theme. Grab the code below, paste it in your functions.php and save the changes:

function strip_img_dimensions( $html, $post_id, $post_image_id ) {
$html = preg_replace( '/(width|height)="d*"s/', "", $html );
return $html;}
add_filter( 'post_thumbnail_html', 'strip_img_dimensions', 10, 3 );
add_filter( 'post_html', 'strip_img_dimensions', 10, 3 );

After saving the changes, you will receive image attachments without height and width attributes in the markup. Hope you found it useful. Thanks :)

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

Related Posts:

WordPress featured thumbnails allow you to add a featured image to your posts. If your WordPress theme has this functionality, then you may set a featured thumbnail to your post by using the Featured Image meta box by clicking the Set Featured image link and u...
WordPress automatically adds its current Version number to the head section of the themes. If you view the source of a WordPress-based website, you may find out the WordPress version it is using. Below given is the meta tag that carries that version informatio...
It’s so common on the internet to have your content stolen. People often scrape your entire hard-worked content and put it over on their sites. That includes image hotlinking too, when the images hosted on the web server paid by you, being used by someone else...