Julien Melissas

Setting the alt attribute from an ACF image object

Introduction

Julien Melissas

Julien Melissas

I'm a Web Developer, Foodie, and Music Lover/Maker living in Asheville, NC. I make things on the web at Craftpeak & JM Labs.


LATEST POSTS

Browsersync Server is your little development friend 08th January, 2018

maybe-rgba() sass function 16th December, 2017

Code

Setting the alt attribute from an ACF image object

Posted on .

You want to make sure your site always has an alt attribute for every single <img> tag for usability reasons, right? Yes. The answer to that question is yes.

The problem is that not every person is going to go in there when uploading images and add an alt tag. They might do it, but they also might not. Especially when bulk-uploading images to things like an ACF Gallery.

Let’s remember that WordPress gives a few fields when uploading an image:

  • title (filled in automatically by the name of the image)
  • description
  • alt text
  • caption

This might be how you would do it:

If you’ve got an ACF image field or ACF Gallery that returns an ACF image object you might do it like this:


<?php
// Get Image Object
$image = get_field('image');

// If there is an image...
if($image) {
  // we'll grab the thumbnail size of the image
  $image_thumbnail = $image['sizes']['thumbnail'];
  // grab the 'alt' attribute
  $image_alt = $image['alt'];
?>

  <img src="<?php echo $image_thumbnail ?>" alt="<?php echo $image_alt ?>">

<?php
} //endif $image
?>

That would normally be fine except for if the alt tag isn’t filled in you’re going to get this:
<img src="path/to/image" alt="" />
And nobody likes blank alt attributes.

A simple solution!

Luckily, this isn’t a very hard problem to solve. A simple function like the one I wrote below checks if you have an alt filled in and if not it will use the title of the image as a fallback, so there’s always something in there. All you have to do is pass it the image object. You can place this code in your functions.php or something.


<?php
// Set the alt of an image from an ACF Image Object
function acf_image_set_alt($image) {
  $alt = $image['alt'];
  
  if (!empty($alt)) {
    return $alt;
  } else {
    return $image['title'];
  }
}
?>

And you would use it like this:


<?php
// Get Image Object
$image = get_field('image');

// If there is an image...
if($image) {
  // we'll grab the thumbnail size of the image
  $image_thumbnail = $image['sizes']['thumbnail'];
  // grab the 'alt' attribute
  $image_alt = acf_image_set_alt($image);
?>

  <img src="<?php echo $image_thumbnail ?>" alt="<?php echo $image_alt ?>">

<?php
} //endif $image
?>

And that’s it!

If you have a better way to do this, please let me know in the comments below.

Julien Melissas

Julien Melissas

https://www.julienmelissas.com

I'm a Web Developer, Foodie, and Music Lover/Maker living in Asheville, NC. I make things on the web at Craftpeak & JM Labs.

Navigation