Pro Tip: Use the esc_attr Function to Format alt Tags When Using ACF

Posted on June 13, 2019 - 1 Minute Read

Intro

Originally this article recommended using the htmlentities function. However, after a lot of helpful feedback, I've learned it's best practice to use esc_attr

If you're rendering images with ACF, make sure you run the alt text against the htmlentities esc_attr function. Why? Because there's a chance that the alt text could contain quotation marks "".

acf image field setup

If it does, it will break the formatting of the alt tag as seen below.

Before

example of incorrectly formatted alt tag

<?php
	$image = get_field('banner_image');
	$url = esc_url($image['url']);
	$alt = $image['alt'];
?>
...
<img src="<?php echo $url; ?>" alt="<?php echo $alt; ?>" />
<img src="..." alt="Zapp Brannigan drinking " champaggan""="">

After

example of correctly formatted alt tag using esc_attr

<?php
	$image = get_field('banner_image');
	$url = esc_url($image['url']);
	$alt = esc_attr($image['alt']);
?>
...
<img src="<?php echo $url; ?>" alt="<?php echo $alt; ?>" />
<img src="..." alt="Zapp Brannigan drinking &quot;Champaggan&quot;">
Categorized In:Tagged In: