When to use esc_html and when to use sanitize_text_field?

esc_html() is more or less lossless — it just turns HTML markup into encoded visible text, so that it’s not rendered as markup by browser.

Semantically it’s escape, so it’s meant to be used to make output to page safe.

sanitize_text_field() however actually removes all HTML markup, as well as extra whitespace. It leaves nothing but plain text.

Semantically it’s sanitize, so it’s meant to be used to make input being saved safe.

Leave a Comment