Don't know where to look?

You can search all my notes here

Add image proportions as a class to WordPress images

The following code will add the classes img-ratio-squareimg-ratio-lt-square or img-ratio-gt-square to every image that’s printed using wp_get_attachment_image()

functions.php
php
<?php

add_filter('wp_get_attachment_image_attributes', function ($attr, $attachment, $size) {
  list($src, $width, $height) = wp_get_attachment_image_src($attachment->ID, $size);
  $image_ratio = $width / $height;
  $ratios = apply_filters('image-ratios', ['square' => 1]);
  $classes = array_filter([$attr['class'] ?? '']);
  foreach ($ratios as $name => $ratio) {
    $classes[] = 'img-ratio-' . ['lt-', '', 'gt-'][($image_ratio <=> $ratio) + 1] . esc_attr($name);
  }
  $attr['class'] = implode(' ', $classes);
  return $attr;
}, 10, 3);

To use this code, simply copy it into your functions.php (or any other file that gets included into your functions.php)

If you want to check other proportions than just square, you can add the following code to your functions.php:

php
<?php
add_filter('image-ratios', function ($ratios) {
  $ratios['rect'] = 2;
  return $ratios;
});

The keys of $ratios will determine the class-names and the values are the ratios as width / height to compare with.

How to use this

One example use case for these classes would be to center an image inside a square box:

php
<div class="img-contain-square">
  <?php echo wp_get_attachment_image($id, 'full') ?>
</div>
css
.img-contain-square {
  /* CSS-Hack to make the div square */
  width: 100%;
  padding-bottom: 100%;
  font-size: 0;
  /* All children will have to be positioned absolutely */
  /* to not mess with the proportions */
  position: relative;
}

.img-contain-square img {
  /* Position absolutely and center inside the parent */
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  /* By default make the width 100% */
  width: 100%;
  height: auto;
}

.img-contain-square .img-ratio-lt-square {
  /* For portrait images switch to sizing by height */
  height: 100%;
  width: auto;
}

Notice how this emulates background-size: contain using an actual image tag, with a wide browser-support and without the need for JavaScript

Comments

Post-Meta
  • Published: May 4, 2020
  • Last modified: May 4, 2020
Included files
  • functions.php
  • readme.md
Download all