How to Remove Image Size Attributes in WordPress

Every time you upload an image to a WordPress-powered website, WordPress includes width and height attributes to the line of code that goes with the image when it is added to a post. While it is good as it directly tells browsers what width and height to give to the image when it is rendered, in this era of responsive designs it means the image dimensions are inflexible. The image will look the same regardless of the browser width of the device where it is displayed.

Here are the steps to prevent WordPress from inserting width and height attributes to images and stripping the already existing attributes from images — without you manually deleting the attributes from the codes in the database.

1. Add the following lines of code to the functions.php file.
// Remove width and height attributes from image tags
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' );
2. Insert the following jQuery code to the JavaScript assets for the website.
// Remove width and height attributes from image tags
jQuery(document).ready(function ($) {
$('img').removeAttr('width').removeAttr('height');
});