You are here:Home » WordPress » Smarter Filtering Width And Height of Images

Smarter Filtering Width And Height of Images

Whenever you upload an image using the WordPress media library and add this image to your post, WordPress will automatically add the image Width and Height attribute in the image element.
This is fine for most themes, but there are other times when you don't want WordPress to add these attributes. The benefit of not adding these attributes is that you can leave any sort of dimensions to the CSS.
If you want to remove these attributes from the image elements it can be done with a simple regular expression search and replace and attach this to two WordPress filters.
  • post_thumbnail_html - Filter any post thumbnails
  • image_send_to_editor - Filter the HTML when adding a image to the editor
Add the following code to remove the width and height attributes from the image elements.

add_filter( 'get_image_tag', 'remove_width_and_height_attribute', 10 );
add_filter( 'post_thumbnail_html', 'remove_width_and_height_attribute', 10 );
add_filter( 'image_send_to_editor', 'remove_width_and_height_attribute', 10 );
function remove_width_and_height_attribute( $html ) {
   return preg_replace( '/(height|width)="\d*"\s/', "", $html );
}

0 comments:

Post a Comment