WordPress – how to strip inline image width and height attributes (for responsive designs)
Want to make a new responsive WordPress theme and need to remove the automatically generated width and height attributes? For example, WordPress is generating image code like this:
When what you need is:
Exactly the same, sans the width and height attributes. Well, here’s how (filter info from here)
1. Open your theme’s functions.php (e.g. wp-content/themes/*your theme*/functions.php
2. Add the following filter:
add_filter( 'post_thumbnail_html', 'remove_thumbnail_dimensions', 10 ); add_filter( 'image_send_to_editor', 'remove_thumbnail_dimensions', 10 ); function remove_thumbnail_dimensions( $html ) { $html = preg_replace( '/(width|height)=\"\d*\"\s/', "", $html ); return $html; }
This will remove the inline width and height attributes for thumbnails and images added through the editor, however, it won’t remove them from images retrieved through wp_get_attachment_image or other related functions (as there are no hooks in there).
Hi Ben,
I thought you might find this interesting. I first found your blog post, and then found this one the WP support forum:
http://wordpress.org/support/topic/resizing-images-for-a-responsive-design
The answer probably lies in the CSS for the TwentyEleven theme, which is responsive:
/* Images */
.entry-content img,
.comment-content img,
.widget img {
max-width: 97.5%; /* Fluid images for posts, comments, and widgets */
}
img[class*=”align”],
img[class*=”wp-image-“] {
height: auto; /* Make sure images with WordPress-added height and width attributes are scaled correctly */
}
img.size-full {
max-width: 97.5%;
width: auto; /* Prevent stretching of full-size images with height and width attributes in IE8 */
}
Looks to me like images with an explicit width and height declared on them require a resetting of the width and/or height to ‘auto’ in order to take advantage of responsive resizing.