Before outputting any data you should correctly escaped it for the context where it is rendered.

What does escape mean?

Escaping is the process where we strip off any unwanted data before outputting it in HTML pages. This data can be anything from script tags or malformed HTML.

You should always escape your data in order to prevent XSS (Cross-site scripting) attacks.

When to use esc_attr ?

esc_attr should be used when you want to escape an HTML attribute, such as class, placeholder, type, title etc. For a better understanding check the examples bellow:

<?php echo '<div class="'.esc_attr( $some_variable ).'"></div>';  ?>

or

<?php echo '<textarea placeholder="'.esc_attr( $some_variable ).'"></textarea>'; ?>

When to use esc_html ?

esc_html should be used when you want to escape HTML blocks. Follow the examples for a better understanding:

<h1><?php echo esc_html( $some_variable ); ?></h1>

or

<div class="my-div"><?php echo esc_html( $some_variable ); ?></div>

When to use esc_url ?

esc_url should be used when you want to escape URL’s (links). Follow the examples for a better understanding:

<a href="<?php echo esc_url( $some_url ); ?>">My url text</a>

or

<form method="post" action="<?php echo esc_url( $some_url ); ?>">

Hope this article clears your mind, and gives you a better understanding on when to use the WordPress escape functions.

Happy coding!

8 Shares