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...
To hide featured images on a WordPress page without using list items, you can follow these steps:Open your WordPress dashboard and go to the page where you want to hide the featured image.Click on &#34;Pages&#34; in the left-hand menu and select the desired pa...
To upload images into a MySQL database, you&#39;ll need to follow a few steps:Create a table: Begin by creating a table in your MySQL database that will store the images. The table should have columns to hold the image data, such as an &#39;id&#39; (primary ke...