Using WordPress ‘esc_attr()’ PHP function

The esc_attr() WordPress PHP function is used to escape HTML attributes. It’s crucial for security as it helps to prevent Cross-Site Scripting (XSS) attacks by ensuring that characters like quotes, less than, and greater than are properly encoded.

Usage

Here’s a general use case for esc_attr():

$attribute = 'This is a "test" attribute';
echo '<div class="my-class" title="' . esc_attr( $attribute ) . '">Hello, World!</div>';

In this example, the value of $attribute is passed through the esc_attr() function to escape any HTML characters. This is particularly useful when the attribute value is dynamic and might contain unexpected characters.

Parameters

  • $text (string, required): The text that needs to be escaped.

More information

See WordPress Developer Resources: esc_attr()

  • The function was introduced in WordPress 2.8.0.
  • It’s located in wp-includes/formatting.php.
  • Related functions: esc_url(), esc_textarea().

Examples

Escaping an HTML attribute

This will escape the text string to be used as an HTML attribute.

$title = 'This "is" a title';
echo '<h1 title="' . esc_attr( $title ) . '">Hello, World!</h1>';

The title attribute in the <h1> tag is safely escaped using esc_attr().

Escaping a form field’s value

The following example escapes a form input’s value.

$user_name = $_POST['username'];
echo '<input type="text" name="username" value="' . esc_attr( $user_name ) . '">';

The value of the user_name is escaped to prevent XSS attacks.

Escaping a dynamic attribute

This example escapes a dynamic attribute in an HTML tag.

$dynamic_attribute = 'data-custom-value';
$value = 'This is a "test"';
echo '<div ' . esc_attr( $dynamic_attribute ) . '="' . esc_attr( $value ) . '">Hello, World!</div>';

The dynamic attribute and its value are both escaped.

Incorrect usage of esc_attr()

This demonstrates what happens when esc_attr() is used incorrectly, without quotes around the attribute’s value.

$attribute = 'This is a "test"';
echo '<div class=my-class title=' . esc_attr( $attribute ) . '>Hello, World!</div>';

This is unsafe as the value of the attribute isn’t quoted.

Correct usage of esc_url() with esc_attr()

This shows the correct way to use esc_url() in conjunction with esc_attr().

$src = 'https://example.com/image.png';
echo '<img src="' . esc_url( $src ) . '">';

The URL for the src attribute is correctly escaped using esc_url(), removing the need for esc_attr().