When building custom functionality into WordPress, it’s important to make sure that you’re properly sanitizing data. WordPress provides an array of utility functions for doing this.

But there are times when completely sanitizing the input may be too much. For example, say you’re working on a widget that has a text field and you’re comfortable with allowing the user to input styles and markup but want to remove any JavaScript. Using strip_tags and strip_slashes is overkill, obviously. These would reduce the input into nothing but the raw text.

Here’s a simple way to removing JavaScript tags from input fields while still supporting inline CSS and HTML markup:

Say we’re working with a widget and the user wants to provide text that looks like this:

<script type="text/javascript">alert('Hello world!');</script><strong>Hi There!</strong><p>My name is Tom.</p>

And we want the end result to look like this:

<strong>Hi There!</strong><p>My name is Tom.</p>

A simple regular expression will allow you to parse out the script tags (and it accounts for new lines, too):

preg_replace( '/<scriptb[^>]>(.?)</script>/is', '', $input );

Practically speaking, here’s a gist of what the update function may look like:

A word of caution: This way is suitable for smaller cases, but I don’t recommend this for trying to sanitize data for larger fields or larger systems.

Category:
Tips
Tags:
,

Join the conversation! 2 Comments

  1. Hey Tom,
    thanks for post. I’ve an issue which have to be solved asap. I came across to your website, maybe you can help me.

    An alert box has been appearing on a (WP) website of my client for a few weeks; I have already found out why. This happens because a funny person has put a alert into one of the input fields.
    I have removed it from the database currently; but, how is it possible to disable this function?

    here the link to the wp plugin support forum, Maybe you can reply directly here: http://wordpress.org/support/topic/how-to-disable-in-a-input-field-alert-box-problem?replies=1

    Here the link to the website with the petition

    Thanks in advance

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.