Software, Development, and WordPress

Remove JavaScript Tags From WordPress Input Fields

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.


  1. Serkan

    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:

    Here the link to the website with the petition

    Thanks in advance

    • Tom McFarlin

      Hey Serkan,

      Without knowing more about your particular blog, I can’t offer support. I wouldn’t mind helping you out, though this is something that’d fall under premium support. If you’re interested, let me know and shoot me a note via my contact page.

      All the best!

Leave a Reply

© 2020 Tom McFarlin

Theme by Anders NorenUp ↑