WordPress HTML escaping for saved textarea data

While creating an admin area for a custom plugin I was working on for a client I had a need to add a WP Editor textarea to allow the client to add/edit richtext for use by the plugin. Everything appeared to work great until the client tried to add links to the textbox. They were being saved with quotes, ampersands, etc escaped to their full unicode names ($quot;, $amp;, etc). Slashes were getting doubled up.

The Solution

After some quick Googling I found a surprisingly mixed response of solutions which unsurprisingly did not work. They either introducted XSS vulnerabilities or destroyed the formatting of the richtext. The actual solution is twofold and will involve editing both your method of saving the text as well as displaying it anywhere (including in the editor itself).

Anywhere you are saving the content of the WP Editor textbox, you must run it through this function:

//$content is your richtext content from the WP Editor.
wp_specialchars_decode($content, $quote_style = ENT_QUOTES);

Next, anywhere you want to output this data properly you must run it through two functions:

stripslashes(wpautop($content));

stripslashes() will prevent any existing slashes from being escaped with more slashes and wpautop() will convert any double line breaks into paragraph HTML entities.

Leave a Reply

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