Easier way to make sure all strings are escaped in WordPress themes

We all know we should escape all the strings in a theme. WordPress theme review guidelines require it, and so does Themeforest.

After working on a theme for a longer period of time, it’s quite possible that you’ve slipped somewhere with unescaped echoes. If you’re going commando on your own – you still need to escape every little thing and be twice as careful if there are no additional set of eyes on your code.

This has happened to me time and time again, and after about a 100 rejections on Themeforest (throughout all my theme submissions), I think it’s about time to start avoiding some of the rejection reasons. One of which is validation.

Searching for echo is just not going to cut it. In my code – that’s just too many lines to go over the code. On top of that – when searching for a simple echo, it’s easy to miss a problematic echo statement among all the wp_kses and esc_attr functions I’ve used.

And as always…

Regex to the rescue

I’m searching all files and folders with this pattern in phpStorm, but I bet this works in Sublime Text and probably Atom too:

^(?!.*kses|.*esc_|.*\sget_|.*\ssanitize).*echo.*$

This is going to search for all echo statements, that don’t contain kses, esc_, get_, sanitize.

I think I can ignore get_ functions because I trust WordPress to have already sanitized at least that content.

An important part is the \s before get_ and sanitize because  I may have written a function that has get or sanitize in the function name, and we don’t want to ignore those, so ignore them only if the function starts with a space character so that my prefixed dastheme_get_something() functions are not going to be ignored.

Finally – this is going to include all __() and _e() functions. If you find them, make sure you’ve properly sanitized them. You should be using esc_html__() instead anyway.

Leave a Reply

Your email address will not be published. Required fields are marked *