Alt text (short for “alternative text”) is an incredibly useful piece of markup that can be added to images. It is extremely useful for both accessibility and SEO purposes. It allows visually impaired readers as well as search engines to understand what content is contained within an image.
We do a lot of custom theme development here at Endo Creative and one of our favorite tools to use is Advanced Custom Fields (ACF). We were recently working on a project where we needed to pull in both the image url and the image alt text as well as have the ability to add specific classes. We created a simple function since we would need to do this many places throughout the theme utilizing both ACF fields and ACF sub-fields.
Here’s the function we added to our custom-functions.php file:
Here’s a breakdown of how each variable is being used:
$imagefield
– is the name of your custom field in ACF
$postID
– lets the function know which post the image is tied to
$imagesize
– is set to ‘full’ by default, but you can specify the images size if needed
$subfield
– we used a lot of ACF repeaters and groups in this project, so depending on what we were doing sometimes the image was an ACF subfield… this is set to ‘false’ by default but can be changed to ‘true’ if needed to use the correct ACF function
$class
– an empty string by default, but can be used to add classes to the returning image element
First the function checks to see if it is looking for an ACF field or an ACF sub-field. Then the function will then use ACF’s function of get_field()
or get_sub_field()
to pull in the image accordingly.
Note: You will want to set the Return Format to Image ID.
Next the function will use a WP function to get the source url of the image. It will then use a WP function to get the alt text associated with that image. Finally, the function will return an image element with the source url, any classes you have added, and the associated alt text.
This can then be easily echoed out in the theme while keeping your template code from getting too cluttered.
Here’s an example:
Here we are running a WP Query to pull in photos of each team member to be displayed on the team page. We created a custom post type for team members and added an ACF field for their serious photo and an ACF field for their funny photo. We’re alternating between photos upon hover.
And here’s another:
Here there are multiple testimonials in this ACF repeater field, so the function will get the associated image (the testimonials are being looped over in a while
loop) using the ACF sub-field function, pulling in the alt text and giving it the class of testimonial-img
.
While there are multiple ways of accessing alt text when pulling an ACF image into a theme, we’ve found this little function to come in handy on multiple projects now. We hope it helps you too 🙂