How and why to prevent WordPress to add image dimensions

WordPress will automatically add image dimensions, width and height, to every image you place. While this can be good in many cases, responsive design sometimes works best when no dimensions are set.

To prevent WordPress to add dimensions to your content images and thumbnail you’ll need to  add a few lines to your functions.php file in your theme. If your theme doesn’t have a functions.php you can simply create a file named just that.

Simply copy the code below and paste in into functions.php and the following will happen

  • Your post thumbnail image tag will not have width and height set.
  • Images you send to the editor will be stripped from dimensions as well.
  • Already published posts with images will be parsed before presented to have the dimensions of images removed.
add_filter( 'post_thumbnail_html', 'remove_thumbnail_dimensions', 10 );
add_filter( 'image_send_to_editor', 'remove_thumbnail_dimensions', 10 );
add_filter( 'the_content', 'remove_thumbnail_dimensions', 10 );

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

You can also view the source on gist.

Now you’re set to continue publishing great responsive stuff in your WordPress site!

Thoughts and comments

  1. Are there any other steps besides copying the code into functions.php? Gave it a try, and all of my images (thumbnails and full-sized) still have height and width tags associated with them when I insert into the editor and when I load the published pages. Any idea what’s up?

    1. The third filter (the_content) also removes the dimensions when presenting a post or page, so while the dimensions are still present in the editor in admin, they are not when viewing the content. Try view source on a published post with an image. 🙂

  2. the regexp seems to have got a bit mangled when you posted.

    Should be:

    $html = preg_replace( ‘/(width|height)=”\d*”/s’, “”, $html );

    Surely? (Wonder what the chances are that this comment will be equally mangled?).

Share your thoughts on this

Your email address will not be published.