How to remove height and width attributes from images in WordPress

Nowadays, building responsive websites is becoming more and more common. That forces us to make sure no matter what CMS or platform we are working with, the end result is what we need it to be for the site display as desired. Especially, if a client takes over further content input who has minimal or no knowledge of any technical aspects.

Lately, I have been working quite a bit with projects that are in WordPress and have been running into instances when I know a client will want to embed images into articles or pages, and WordPress by default embeds images’ width and height attributes, and we all know that when going responsive, those aren’t our best friend. Expecting your client to go back and manually remove it each time may not be all that ideal and bulletproof, and even I was tired of doing the same on my site, so I asked my friend Google and thankfully found a quick and easy solution on WP Daily Bits.

All you have to do is to add the following code into your functions.php within your theme and you are good to go.

add_filter( 'post_thumbnail_html', 'remove_width_attribute', 10 );
add_filter( 'image_send_to_editor', 'remove_width_attribute', 10 );

function remove_width_attribute( $html ) {
   $html = preg_replace( '/(width|height)="\d*"\s/', "", $html );
   return $html;
}

Just be aware, if you already have images on your site that may have height and width attributes, you will need to remove those manually. However, any images from now on that you will add to your site, won’t have them anymore. Happy embedding! 🙂

Comments

  1. whiwo says:

    doesn’t work

  2. Subrata Sarkar says:

    Works well for featured images and images uploaded via editor. But how can I remove width and height attributes for user avatar?

    • It all depends how user avatars are rendered on the page within your theme. You may either have a plugin that you would need to customize or if it’s part of your theme, then tinker with the code there, as usually the HTML is usually predefined. So it’s all up to you and your skill level if you can figure out where to go to make the necessary edits.

  3. Juan Maldonado says:

    Thank you! This really helped a lot.

  1. Required
  2. Required, but never shared