Wordpress - Which WP functions do you need to use esc_html() or esc_url() on?

Any that return data.

  • If a function outputs internally, then it's taken responsibility for escaping
  • if a function returns the data for use, it will be unescaped to avoid double escaping, it's your responsibility

This is because you should always late escape so that there is no doubt if a variable is escaped.

If the output of APIs such as home_url were pre-escaped, then this would no longer be true. It would also introduce double escaping, which can be used to break past escaping in some scenarios.

Some further notes:

  • don't bother to escape static strings, it's pointless
  • don't try to wrap functions like the_permalink in esc_url etc, escaping functions are still functions, they aren't magic modifiers/highlighters telling PHP to secure something.
  • Don't return complex HTML fragments in variables, return data, data doesn't need to be escaped, but escaping a complex HTML fragment is not easy, and usually impossible to do safely
  • When using shortcodes/filters, make sure to escape the bits you add/modify, but leave the rest alone and trust it's been escaped, it's not your responsibility to escape output generated elsewhere in these situations. Having said that, don't trust it as an input either if it's being used to guide your own code

Any output of untrusted data (including data from database) must be sanitized. WordPress Codex describes available functions: https://codex.wordpress.org/Data_Validation

Code sniffers, following WordPress Coding Standards, require to sanitize output even from WordPress core functions. You can turn on such code sniffer in PhpStorm, for example.

Sometime such a requirement is excessive, but it is better to follow coding standards to have more reliable code.