Using WordPress ‘attribute_escape()’ PHP function

The attribute_escape() WordPress PHP function is used to escape HTML attributes. Essentially, this function makes sure any text used within an HTML attribute is safe and does not break your HTML. This function is very similar to the esc_attr() function.

Usage

Let’s say you have a variable $user_input that you want to include within an HTML attribute. You can use the attribute_escape() function like this:

$user_input = 'something from the user';
echo '<div class="' . attribute_escape($user_input) . '">Hello World!</div>';

Parameters

  • $text (string) – The text that needs to be escaped.

More information

See WordPress Developer Resources: attribute_escape()
This function was introduced in WordPress 2.8.0. It’s worth noting that attribute_escape() has been deprecated since WordPress 2.8.0. It’s recommended to use esc_attr() instead.

Examples

Escaping a Class Name

In this example, we are using user input as a class name for a div.

$user_class = "user-defined class";
echo '<div class="' . attribute_escape($user_class) . '">This is a div with a user defined class.</div>';

Escaping an ID

Here we are using user input as an ID for a div.

$user_id = "user-defined id";
echo '<div id="' . attribute_escape($user_id) . '">This is a div with a user defined ID.</div>';

Escaping an Attribute in an Anchor Tag

This time, we are escaping the title attribute in an anchor tag.

$user_title = "user-defined title";
echo '<a href="#" title="' . attribute_escape($user_title) . '">Link with a user defined title.</a>';

Escaping a Data Attribute

In this scenario, we’re escaping a data attribute.

$user_data = "user-defined data";
echo '<div data-info="' . attribute_escape($user_data) . '">This is a div with a user defined data attribute.</div>';

Escaping an Image Alt Tag

Lastly, we are escaping the alt attribute of an image tag.

$user_alt = "user-defined alt";
echo '<img src="image.jpg" alt="' . attribute_escape($user_alt) . '">';

In each of these examples, the attribute_escape() function ensures that the user-defined values do not break the HTML structure by removing any characters that are not allowed in HTML attributes.