7

I've come across situations where people have used either esc_html() or esc_url() with certain WP functions such as home_url('/'). An example being in the opening anchor tag of <a> link back to the homepage such as this:

<a href="<?php echo esc_url( home_url( '/' ) ); ?>"> 

How do you know which WP functions need to be escaped and does it matter if you use esc_html() or esc_url()?

Any advice or guidance would be wonderful.

10

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
3

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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