Prevent XSS (Cross-Site Scripting) by escaping values in your WordPress templates

Escape all the things (meme)

If you are developing a WordPress theme or plugin then it is important to make it as secure and robust as possible. One way to do this is to properly escape values that you use in your project so that XSS (Cross-Site-Scripting) is prevented.

For instance, lets say that in your WordPress site you have created a custom piece of functionality that takes some user data, lets say something simple like a signup form:

Feedback form example

And lets say that elsewhere in WordPress you output this into a table of form fields without any escaping (this is a super simplified example).

A malicious customer could enter there name as: Malicious User" onclick="alert( 'Attack!' );"

When the data is loaded on your unescaped form, the first " would end the value="" attribute, and the onclick="" would be inserted into the form, resulting in the following for the input is clicked:

XSS Alert Box Example

True this would be a pretty mild piece of malicious code, but as you can imagine this could be exchanged for some very nasty code indeed.

Escape all the things

This horrible and malicious attack could have just been avoided if we had escaped the attribute using esc_attr() like so:

<input type="text" value="<?php echo esc_attr( $my_value );?>"/>

There are a load of different escapes that you can use for a whole variety of scenarios (e.g. escaping URLs, escaping Email Addresses), and there is a fantastic section in the WordPress handbook all about Escaping.

Something that is equally important is sanitising your data, which you should do whenever you receive data from the user (remember to sanitise when you get it, escape when you output it). Information about sanitising is available in the WordPress handbook also.

Matt Watson

Technical Lead at Make Do
Matt Watson is the co-founder and technical lead of WordPress agency Make Do. Matt loves writing and learning about code, and considers himself lucky to be doing what he loves for a living. Find out more about Matt, or get in touch to hire Matt for your project.

Leave a Reply