esc_attr

Home » Functions » esc_attr

Function Name: esc_attr

WordPress websites can sometimes be vulnerable to security risks such as cross-site scripting attacks. The esc_attr function is used to sanitize and escape data that is meant to be used as an HTML attribute. This function ensures that any special characters in the data are converted into their corresponding HTML entities, thereby preventing malicious code injections.

The esc_attr function takes one parameter, which is the string of data to be sanitized. It can be used to sanitize data such as post titles, post content, widget titles, and other user-generated data that will be displayed on the front-end of the website.

Example Usage Code:

Let’s say we have a variable $title that contains a post title that a user has submitted through a form. We want to display this title on the front-end of the website, but we need to sanitize it first to prevent any malicious code injections. We can use the esc_attr function like this:

$title = ‘My Post Title’; // User-generated data $sanitized_title = esc_attr( $title ); // Sanitize the data echo ‘

‘ . $sanitized_title . ‘

‘; // Display the sanitized title as an HTML header tag

In this example, the esc_attr function is used to sanitize the $title variable before it is displayed as an HTML header tag. This ensures that any special characters in the $title variable are properly escaped, thereby preventing any malicious code injections.

Learn More on WordPress.org

Register an account to save your snippets or go Pro to get more features.