When working with themes and plugins, it’s a common practice to escape WordPress data. Honestly, this is a standard practice in all web development:

Whenever you’re retrieving information from the database to display to the user, it should be validated and escaped so that nothing but clean, readable text is rendered to the user.

In WordPress, you’re likely to see this in one of two ways (or maybe both ways depending on your setup):

  1. You’re retrieving information from the database via get_option and then displaying it to the user.
  2. You’re retrieving information from the cache and displaying it to the user.

There may be other ways that you’re grabbing the information, but the specifics beyond what’s above are outside the purpose and scope of this post.

Instead, the point I’m working towards is that we should escape WordPress data in the context of a template file or a view rather than in the context of a function.

Why We Late Escape WordPress Data

I like to keep a strong separation of concerns between the application layer and business logic and the view or templates. That is, anything that needs to communicate with WordPress or operate on data according to the requirements of the project happens in the server-side code.

Because of that, I have a tendency to want to both sanitize and validate and escape all information on the server-side and then render it to the user.

And I don’t necessarily think there’s anything wrong with doing this, but I do believe that it presents problems with maintenance or with reviewing existing code before actually working on it.

Late Escape WordPress Data: An Example

Though this requires we mix our templates with a little more PHP than we may like (depending on how we’re working with views), the advantages far outweigh some slight mixing of languages.

For example, opting to late escape WordPress data yields the following:

  • When performing a code review, it’s easy to see if the programming is properly escaping data by merely looking in the context of the template. If a programmer is doing this in a function, there may be several places that we’d need to look to find where the escaping is happening.
  • If the code on the server-side is refactored or changed, and the escaping happens on this side of the application, we may inadvertently forget to escape the information in the new or updated function. Looking at the view code would not tell us if the data is escaped or not.
  • This allows us to have more readable view code by looking at an element whether or not it’s a span, inputtextarea, or something else and know if we’re escaping data or not.

Yes, there are other reasons for opting to late escape WordPress data (and there are arguments for escaping a little earlier).

But the driving motivation behind this post is from my experience as it relates to working on custom plugins for others, working on my plugins, and performing code reviews for on other code.