Optimize Your Images: A Guide on Removing Thumbnail Size Dimensions in WordPress
By default, WordPress assigns dimensions to featured images, but these may not always suit your website. If you’re not keen on responsive design, your images might appear messy with incorrect width and height. This becomes crucial when crafting a custom theme or template, and you want to get rid of those default dimensions. Fortunately, it’s a breeze to achieve this using a simple filter hook. Not only does this remove the default width and height, but it also empowers you to define your custom sizes effortlessly.
So we will be using apply_filters hooks to filter the post thumbnail.
apply_filters( 'post_thumbnail_html', '$variables' );
This post_thumbnail_html hook will pass 5 variables to your hooked function.
$html
– Output HTML of the post thumbnail$post_id
– Post ID$post_thumbnail_id
– Attachment ID of the image$size
– Requested or default size$attr
– Query string or array of attributes
Why This Matters: Default Width and Height in WordPress
When you upload images via the Image Uploader in Featured image for your posts or pages, WordPress automatically includes default width and height attributes in the HTML <img>
tag. For instance:
<img width="123" height="456" src="http://example.com/image.jpg">
The Solution: Removing Hardcore Width and Height in WordPress
To remove these default dimensions, simply add the following code to your theme’s functions.php
// Removing Hardcore Width and Height in WordPress
add_filter( 'post_thumbnail_html', 'pp_remove_thumbnail_dimensions', 10, 3 );
function pp_remove_thumbnail_dimensions( $html, $post_id, $post_image_id ) {
$html = preg_replace( '/(width|height)=\"\d*\"\s/', "", $html );
return $html;
}
And that’s it! The next time you insert an image into a post thumbnail, the default width and height attributes won’t be there.
Additional Resources: Plugins for Easy Removal
If coding isn’t your thing, there are plugins available in the WordPress Repository that make it a breeze to modify or remove image size attributes:
Optimize your images and enhance your WordPress experience!