Remove automatic dimensions from WordPress Image attachments

Strip automatic width and height attributes from WordPress image attachments–handy code snippet to make WordPress images responsive.

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 :)