Artistic photo of sparks flying from angle grinder in use

Adding image focal points to the WordPress media library

I’m a really big fan of flexible image placements for digital design, and a big part of making those placement work is having proper focal points set and easily managed.

I’m not really a photographer’s photographer. I know many would consider it blasphemy to present photos with fluid aspect ratios, but I think it makes sense for most images on websites. So let’s talk about making it easy and manageable to do this in WordPress.

Getting image focal points

I really appreciate that Gutenberg provides a focal picker component when building custom blocks, but the part that feels lacking to me is the visualisation of the selected focal point.

To account for this, I built my own focus visualiser tool a while ago that shows the effect of changing your focal point in real-time for many common aspect ratios, ranging from quite tall to quite wide.

It’s pretty often that the ideal focal point ends up to the side of someone’s face, rather than directly on their eye for example, as the most intuitive placement can provide unintended cropping of important features at more extreme aspect ratios.

Adding focal points to the media library

So now we have a way to get the ideal focal point for our images, let’s sort out a way to store the data in our media libraries!

I already use ACF on basically every WordPress project, so I made use of the feature to link field groups to any attachment that matches all image types. The field group just has the one field – a simple text input labelled ‘focus’. Nothing fancy here. The only important part is I’ve set the default value to be 50%, so if no explicit value is set, hopefully the dead center of any uploaded images is a decent enough fallback.

If you want to try it out quickly, here’s a zipped json file you can import into ACF on your sites.

Making use of the data

The only thing left to do is make use of the data. So here’s how I print the focal point on the frontend:

<?php

echo wp_get_attachment_image($id, 'full', 'false', array('style' => "--focus:" . get_field("focus", $id)));

The main thing to note there is that we’re printing an inline style as the value for a custom property called --focus. In my global stylesheet, I’ve got this:

img {
	object-position: var(--focus);
}

So whenever I want to use an image in flexible placement, I can apply object-fit: cover and have the custom property make sure the most important part of the image never gets cropped out of the flexible placement.

Recent posts