Embedding JS Script Tags in WordPress Posts

When you include javascript in a WordPress post, WP automatically applies formatting to the script tag’s contents, causing script errors. This has led to a large number of workarounds, including: plugins, using custom fields, including every script as a separate JS file, and stripping empty lines from the script (to prevent WP from injecting paragraph tags).

I wanted a solution that would let me quickly inject JS directly into my post content, and wouldn’t require any special prep or have dependencies on third party plugins. After unsuccessfully hunting the web for an answer, I came up with a simple approach that uses a pre tag to prevent WordPress from formatting my code:

<pre class="script"><script>
  // code here.
</script></pre>

Then just add the following to your site styles to prevent the pre tag from displaying:

pre.script {
  visibility: hidden;
  display: none;
}

It’s crazy simple and the script executes properly. I’m kind of shocked that I didn’t run into this approach at all in my search. It makes me worry a bit that there’s some glaring flaw with it, but so far it seems to be working great.

Hopefully this saves someone else some time and frustration.

Note: there’s a chance you may need to disable “Settings > Writing > WordPress should correct invalidly nested XHTML automatically” to prevent WP from encoding characters in your code. I have it disabled normally, but in limited testing I didn’t see any problems with it enabled.

Grant Skinner

The "g" in gskinner. Also the "skinner".

@gskinner

5 Comments

  1. I wonder if this will lead to comment injection though..
    alert(1);

  2. alert(“test”);

  3. Hi Grant, I really wanted this to work, but while plain pre tags preserve whitespace and ampersands, once I put the script tag inside the formatting gets screwed up again. Maybe it’s just my version of WordPress (now 3.7) or my server configuration?

    Whitespace is no big deal, I just run the code through jsmin, but the ampersand problem I can’t figure out how to fix. Maybe stick the code in a pre and eval() it?

  4. Just to follow up, I was able to figure out a way to embed JS without worrying about whitespace and special characters, and I wrote a post about it: http://hyponymo.us/embedding-javascript-in-wordpress/

    Plus, the post has some nifty D3.js-generated interactive charts.

  5. alert(“test”);

Leave a Reply

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