When do I need to use esc_html()? [duplicate]

While this is probably a duplicate of What’s the difference between esc_html, esc_attr, esc_html_e, and so on? I’m going to go ahead and provide an answer anyway, since as @cag8f indicated, there’s not an accepted answer on that question (but I’ll add that I think Tom’s answer there tells you what you need to know).

You need to escape output when there’s a possibility that the output might be changed somewhere or may have some “untrusted” value.

In the case of your example (repeated below),

<?php $title = "Contact"; ?>
<h1> <?php echo $title; ?> </h1>

you do not need to escape this. “Contact” is already set and is a safe value and is not changed. In fact, as written, you are wasting space (and readability) and it really should be just hard HTML.

Now, if you do something to $title, that changes things. You would need to escape the output in that case because you don’t know what the value might be.

For example:

<?php $value = get_user_meta( $user_id, 'some_meta', true ); ?>
<p>My Value: <?php echo esc_html( $value ); ?></p>

This needs to be escaped because you don’t actually know what the value is, and thus you don’t know if it is safe to output. That’s where it needs to be escaped.

It is important to also know the following:

  1. Learn which escape functions do which tasks. Using one that isn’t appropriate for the data could result in not fully escaping the value, or breaking it in some other way. There are escape functions for different data types, so use the correct one.
  2. Know if the data needs to be escaped. If you’re using a WP function that already escapes the data, then you’re double escaping it and that can result in bad output. If you’re not sure, look up the function and review the source.

Leave a Comment