WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

It seems that they do almost same type of job. So...

When should I use esc_html() instead of sanitize_text_field()?

share|improve this question

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.

share|improve this answer
isn't it better to use esc_html for both output and saving? I won't display any markup anyway.. so when would i use sanitize_text_field() ? – yeahman Apr 20 '14 at 14:15
@yeahman "better" how? They are doing distinctly different things. Discarding markup usually used for things where markup isn't expected, for example form that takes a name. – Rarst Apr 20 '14 at 14:37
I mean it stores what the user sees and has input... like you said it's lossless..(e.g. he inputs "the tag <head> is where you should include your css files", he expects to see the <head> in his post). For a name field, i would control the input via validation; isn't it more suited? – yeahman Apr 20 '14 at 15:40
I'm interested in the differences between sanitize_text_field() and strip_tags – myol Jan 29 '15 at 14:24
strip_tags is used in sanitize_text_field() if I am not wrong – yeahman Feb 23 at 19:47

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.