WordPress, by default, will add the width
and height
attributes to image elements. These attributes will override CSS width and height properties. Making images with these dimension attributes responsive is a bit of a hassle, or in some cases cannot be done at all.
Strip Image Dimension Attributes from Inserted Images
Stripping out the image size attributes will make sure that you will have complete control over the image size in CSS. You can use the following code to remove these attributes:
/**
* Removes width and height attributes from image tags
*
* @param string $html
*
* @return string
*/
function remove_image_size_attributes( $html ) {
return preg_replace( '/(width|height)="\d*"/', '', $html );
}
// Remove image size attributes from post thumbnails
add_filter( 'post_thumbnail_html', 'remove_image_size_attributes' );
// Remove image size attributes from images added to a WordPress post
add_filter( 'image_send_to_editor', 'remove_image_size_attributes' );
Just be aware that this code will only strip the site attributes from image tags when an image is a featured image or when an image is added to a post. Existing images that have been uploaded to a post will be unaffected.
Remove width
and height
attributes via JavaScript
For existing posts, you will have to go and remove the width
and height
attributes manually, or you can resort to using a bit of jQuery to solve the problem:
jQuery(document).ready(function ($) {
$('img').removeAttr('width').removeAttr('height');
});
It is very likely that you may want to scope the jQuery selector for your specific use-case, but this will do the trick quite nicely. If you are working on a non-WordPress project, this solution will work as long as jQuery is loaded.
Plugin Solution for Stripping Image Size Attributes
If you aren’t the coding type, or prefer to use a plugin and not add the code to your project, just install the Image Size Attributes Remover plugin.