Adding classes based on height and width are important to avoid image crop or stretching issue. In this blog post we will discuss about how to add the class based on size. For that we will be overriding the action using a filter in our main theme or child themes function.php file. This will add class only if your theme is displaying image with the_post_thumbnail action else it wont add the class to your images.

Following is the correct action for displaying image. This can go into the template where you want to display image.

the_post_thumbnail( '' );

Below is the code which needs to be added in your parent theme or child themes funtions.php.

function bwd_addclass_bd_on_size($attr) {
$image = wp_get_attachment_image_src( get_post_thumbnail_id( get_the_ID() ), "full" );
$width_of_image = $image[1];
$height_of_image = $image[2];
if ( $width_of_image > $height_of_image ){
	$attr['class'] .= ' landscape-img ';
} else{
	$attr['class'].= ' portrait-img';
}
  return $attr;
}
add_filter('wp_get_attachment_image_attributes','bwd_addclass_bd_on_size'); 

You can specify the size of image in CSS by calling following class in your CSS. Following are the classes.

Portrait : landscape-img

Landscape : portrait-img

Note : If you are displaying the images with some other method or format please let us know in comments so we will update our post which support your code.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *